How data types affect step size
What you'll learn: Understand how C automatically adjusts the distance a pointer moves based on the size of the data type it points to.
The "Stride" Concept
When you add 1 to a pointer, you aren't adding a single byte to the memory address. Instead, you are telling the pointer to move to the next available slot of that specific data type.
Think of it like taking a step. A toddler and a giant both take "one step," but the giant covers much more ground. In C, the "size" of the step (the stride) depends entirely on the data type the pointer is designed to handle.
Why size matters
Memory is addressed in bytes. However, different data types occupy different amounts of bytes:
- A
charusually takes 1 byte. - An
intusually takes 4 bytes. - A
doubleusually takes 8 bytes.
If you have an integer pointer and you increment it (ptr++), C knows that to reach the "next" integer, it must skip over 4 bytes of memory. If it only moved 1 byte, you would end up pointing at the middle of the first number, resulting in gibberish data.
Seeing it in action
Look at how the memory addresses jump by different amounts in the example below:
#include <stdio.h>
int main() {
char myChar = 'A';
int myInt = 10;
char *charPtr = &myChar;
int *intPtr = &myInt;
printf("Starting Char Address: %p\n", (void*)charPtr);
printf("Char + 1 Address: %p\n", (void*)(charPtr + 1));
// Usually moves by 1 byte
printf("\nStarting Int Address: %p\n", (void*)intPtr);
printf("Int + 1 Address: %p\n", (void*)(intPtr + 1));
// Usually moves by 4 bytes
return 0;
}
Even though we added 1 to both pointers, the intPtr address increased by 4 (e.g., ending in ...A0 to ...A4), while the charPtr only increased by 1.
The Compiler's Job
The magic happens because of the pointer's type declaration. Because you told C that intPtr points to an int, the compiler handles the math behind the scenes. It multiplies your addition by the sizeof that type.
When you write ptr + n, the hardware actually calculates:
address + (n * sizeof(type))
This allows you to focus on navigating through items (like elements in an array) without manually calculating byte offsets for every different piece of data.
Key takeaway
Pointer arithmetic is "scaled" by the size of the data type; adding 1 moves the pointer forward by exactly one data element, not necessarily one byte.