Incrementing pointers (preview)
What you'll learn: How the increment operator behaves differently when applied to memory addresses rather than regular numbers.
The "Smart Step" behavior
So far, you’ve used the increment operator (++) to add 1 to an integer. If x is 5, x++ makes it 6. However, when you apply ++ to a pointer, C does something much more clever. Instead of just adding one byte to the address, it moves the pointer forward by the size of the data type it points to.
Think of a pointer like a person standing on a sidewalk made of large stone tiles. If each tile represents one int (which usually takes up 4 bytes of space), "incrementing" the person doesn't mean they move forward by one tiny inch. It means they take one full stride to land perfectly in the center of the next tile.
Pointer arithmetic in action
Because different data types take up different amounts of room in your computer's memory, the ++ operator automatically adjusts its "stride" to match.
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30};
int *ptr = &numbers[0]; // Pointing to the first element
printf("Original address: %p\n", (void*)ptr);
ptr++; // Incrementing the pointer!
printf("New address: %p\n", (void*)ptr);
printf("New value: %d\n", *ptr);
return 0;
}
In the example above, if the original address was 1000, the new address wouldn't be 1001. Because an int is 4 bytes, ptr++ jumps the address forward to 1004. The compiler handles the math behind the scenes so that you don't have to remember how big an int or a double is; you just tell the pointer to "go to the next one."
Why this matters
This behavior is the secret sauce behind how C handles lists and arrays. By incrementing a pointer, you can effortlessly step through a sequence of data. It ensures that you always land exactly at the start of the next item, rather than ending up stuck halfway between two pieces of data.
Key takeaway
Incrementing a pointer moves it to the next memory slot based on the size of its data type, not just the next byte.