Sub topic 5
Pointer Arithmetic
Assume you know basic C syntax, arrays, functions, and how to compile a program. Pointer arithmetic is the set of operations that moves a pointer through elements of the same array. It is common in GATE questions because the pointer’s type controls the distance moved.
Moving Through an Array
If p points to an element of an array, adding 1 moves it to the next element, not merely to the next byte. The compiler uses the size of the pointed-to type.
For an int *, p + 1 advances by sizeof(int) bytes. For a double *, it advances by sizeof(double) bytes.
#include <stdio.h>
#include <stddef.h>
int main(void) {
int a[4] = {10, 20, 30, 40};
int *p = a;
printf("%d %d\n", *p, *(p + 2));
p++;
printf("%d\n", *p);
printf("%td\n", &a[3] - p);
return 0;
}The output is:
10 30
20
2p initially points to a[0]. Therefore, *(p + 2) is a[2]. After p++, p points to a[1]. Subtracting p from &a[3] gives the number of elements between them, which is 2.
The result of pointer subtraction has type ptrdiff_t, so %td is the appropriate format specifier.
| Expression | Meaning |
|---|---|
| `p + n` | Pointer `n` elements after `p` |
| `p - n` | Pointer `n` elements before `p` |
| `p++` | Move to the next element |
| `q - p` | Number of elements from `p` to `q` |
| `*p` | Value stored at the pointed-to element |
Validity Rules
Pointer arithmetic is defined only within one array object, including the position just after its last element. A pointer may point one past the array, but you must not dereference that pointer.
For int a[4], a + 4 is valid as a pointer value, but *(a + 4) is invalid. Pointer subtraction is valid only when both pointers refer to the same array, or one points just past it.
Adding two pointers is never valid. Arithmetic such as p * 2 is also invalid. C does not define ordinary pointer arithmetic for void *; use a pointer to a complete object type, or convert to char * when examining raw bytes.
A Reliable Tracing Method
For an output question:
- Write the array indices beside the elements.
- Mark the element each pointer currently references.
- Apply
+,-,++, or--as element movements. - Dereference only after finding the new position.
- Check that every operation stays within the same array.
Exercise
If int a[5] = {4, 8, 12, 16, 20}; and int *p = &a[1];, what are *(p + 2) and &a[4] - p?
Show answer
*(p + 2) is 16, and &a[4] - p is 3.