Adding integers to pointers
What you'll learn: How pointers use data types to "jump" through memory when you perform addition.
The "Step Size" Secret
In C, when you add 1 to a pointer, you aren't just adding a single byte to a memory address. Instead, you are telling the pointer to move forward by one whole data type.
Think of it like a staircase. If you are standing on a staircase where every step is 4 inches tall, taking "one step" moves you 4 inches. If the steps are 8 inches tall, one step moves you 8 inches. In this analogy, the "step height" is the size of the data type the pointer points to.
How it looks in code
C calculates the new address behind the scenes using this formula:
New Address = Current Address + (Number * sizeof(Type))
If an int takes up 4 bytes of memory, adding 1 to an int pointer actually shifts the address forward by 4 bytes.
#include <stdio.h>
int main() {
int numbers[3] = {10, 20, 30};
int *ptr = &numbers[0]; // Pointing to the first element
printf("Starting address: %p\n", (void*)ptr);
// Move the pointer forward by 1
ptr = ptr + 1;
printf("New address: %p\n", (void*)ptr);
printf("Value at new address: %d\n", *ptr);
return 0;
}
If you run this, you will notice the memory address doesn't increase by 1. If the first address ends in 00, the new one will likely end in 04. The pointer "jumped" over the first integer to land perfectly at the start of the next one.
Why this matters
This is why pointers are so powerful for handling arrays. You don't need to know exactly how many bytes a piece of data uses on a specific computer. By simply adding 1, 2, or 10 to a pointer, C automatically handles the math to ensure you land exactly at the start of the next item, rather than accidentally landing in the middle of a piece of data.
Key takeaway
Adding n to a pointer moves it forward by n multiplied by the size of its data type.