Iterating arrays using pointer increments
What you'll learn: How to move through an array by mathematically shifting a pointer rather than using an index.
The pointer as a sliding ruler
In C, the name of an array is actually the memory address of its very first element. If you assign that address to a pointer, you are standing at the "front door" of the array. To visit the next element, you don't need to look up a new index; you simply "step" the pointer forward.
Think of an array like a row of identical houses on a street. Instead of saying, "Take me to the house at index 3," you can stand at the first house and say, "Move one house to the right." In C, we do this using the ++ increment operator.
Pointer arithmetic
When you increment a pointer (e.g., ptr++), C is smart. It doesn't just add one byte to the address. It adds the size of exactly one element. If you have a pointer to an int (usually 4 bytes), ptr++ jumps 4 bytes ahead to the start of the next integer. This allows you to walk through memory precisely, regardless of how large the data types are.
Code example
In the following example, we use a pointer to "walk" through an array until we reach the end.
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
// Point to the first element
int *ptr = numbers;
// Iterate through 5 elements
for (int i = 0; i < 5; i++) {
// Print the value at the current pointer location
printf("Value: %d | Address: %p\n", *ptr, (void*)ptr);
// Move the pointer to the next integer in the array
ptr++;
}
return 0;
}
Why use this method?
While using numbers[i] is often more readable, incrementing a pointer is a fundamental pattern in low-level programming. It is frequently used when processing strings (which are just character arrays) or when performance is critical, as it avoids the repeated calculation of "base address + offset" that happens behind the scenes during indexing. By moving the pointer itself, you are always maintaining a direct reference to your current spot in the data stream.
Key takeaway
Incrementing a pointer (ptr++) automatically shifts the memory address forward by the size of one data type, allowing you to traverse an array step-by-step.