Lesson 36: Pointers Part 3: Pointer Arithmetic
Pointer arithmetic allows us to move a pointer forward or backward through contiguous memory blocks, typically arrays.
The Rule of Pointer Arithmetic
When you add an integer $N$ to a pointer, the address increases not by $N$ bytes, but by $N$ times the sizeof() the data type the pointer points to.
New Address = Current Address + (N * sizeof(data_type))
Example
Assume int is 4 bytes. p starts at address 1000.
c int arr[3] = {10, 20, 30}; int *p = arr; // p is at address 1000
p++; // p moves to the next integer element (address 1004)
printf("%d\n", *p); // Output: 20
p = p + 2; // p moves two integers forward (address 1004 + 8 = 1012) printf("%d\n", *p); // Output: 30
Operations Allowed on Pointers
- Addition/Subtraction of an Integer: Moves the pointer location.
- Increment/Decrement (
++,--): Moves the pointer to the next/previous element. - Subtraction of Two Pointers: Calculates the number of elements between two pointers (the result is an integer, often of type
ptrdiff_t). - Comparison: Pointers can be compared (
==,!=,>, etc.). This is meaningful only if they point to elements within the same array.
Void Pointers
A void * pointer can hold the address of any data type. It is useful for general memory operations. However, you cannot dereference or perform arithmetic directly on a void * because the compiler doesn't know the size of the data it points to.