C Pointer Arithmetic

๐Ÿ“Œ C Pointer Arithmetic

Pointer arithmetic in C lets you perform operations on memory addresses โ€” like adding or subtracting values from pointers. This is super handy when working with arrays or memory manipulation.

๐Ÿ”น What is Pointer Arithmetic?

In C, you can use operators like ++, --, +, and - with pointers. But remember: pointer arithmetic moves in steps of the size of the data type!

๐Ÿ“ Example: Basic Pointer Arithmetic

This example shows how pointers move through an integer array using arithmetic.

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *ptr = arr;

    printf("Current value: %d\n", *ptr);   // 10
    ptr++;  // Move to next element
    printf("After ptr++: %d\n", *ptr);    // 20
    ptr += 2;  // Move 2 steps ahead
    printf("After ptr += 2: %d\n", *ptr); // 40
    ptr--;  // Go back one step
    printf("After ptr--: %d\n", *ptr);    // 30

    return 0;
}
  

Try It Now

๐Ÿ’ก How It Works

  • ptr++ moves to the next memory location (depends on data type size).
  • ptr-- moves back one memory slot.
  • ptr + n jumps n elements forward.

๐Ÿ” Note on Types

If you’re working with int, then ptr++ increases the address by sizeof(int) (usually 4 bytes).

๐Ÿ› ๏ธ Practice Time!

Try using pointer arithmetic on a char array or even a float array. See how the steps differ based on type size!

๐Ÿ“š Summary

  • Pointer arithmetic lets you navigate through memory.
  • Always be aware of the data type โ€” it affects address movement!
  • Use it wisely while looping through arrays or working with dynamic memory.