C Pointer Arithmetic
1. What is Pointer Arithmetic?
-
Pointer arithmetic allows you to move a pointer through memory based on the size of the data type it points to.
-
You can perform arithmetic operations like:
-
Increment:
ptr++→ points to the next element -
Decrement:
ptr--→ points to the previous element -
Addition:
ptr + n→ points tonelements ahead -
Subtraction:
ptr - n→ points tonelements back -
Difference:
ptr1 - ptr2→ number of elements between two pointers
Important: Pointer arithmetic automatically accounts for the size of the data type.
2. Basic Example with int Array
Output:
Notice how pointer moves by 4 bytes each time (for
int) on most systems.
3. Pointer Arithmetic with Array Indexing
-
Array indexing is equivalent to pointer arithmetic:
-
numbers + 2→ address of 3rd element -
*(numbers + 2)→ value at that address
4. Difference Between Two Pointers
Output:
Subtracting pointers gives the number of elements, not bytes.
5. Pointer Arithmetic with char Array (String)
Output:
For
char, each pointer increment moves 1 byte (size ofchar).
6. Key Points About Pointer Arithmetic
-
Only valid on pointers to elements of an array or contiguous memory.
-
ptr++moves to the next element (not next byte). -
ptr + nmovesnelements forward. -
Subtracting pointers gives distance in elements, not bytes.
-
Works for int, char, float, double, etc., adjusting automatically for size.
