Scaling factor in pointer math
What you'll learn: How C automatically adjusts pointer calculations based on the size of the data type it points to.
The "Step" Analogy
Imagine you are standing on a giant ruler marked in inches. If you take one "step" forward, how far have you moved? If you are a mouse, one step might be 1 inch. If you are a human, one step might be 30 inches.
In C, pointers work the same way. When you add 1 to a pointer, you aren't adding a single byte to the memory address. Instead, you are telling the computer to move forward by one data type. C looks at what the pointer is pointing to and automatically "scales" the math to match that size.
Why Scaling Matters
Different data types take up different amounts of space in memory. An int usually takes 4 bytes, while a char takes only 1 byte.
If you have an integer pointer and you write ptr + 1, C knows that to get to the next integer, it must skip over 4 bytes. If it only moved 1 byte, you would end up in the middle of your first number, resulting in gibberish data.
Seeing it in Code
Observe how the address changes differently for a char versus an int in the following example:
#include <stdio.h>
int main() {
char letter = 'A';
int number = 100;
char *pChar = &letter;
int *pInt = &number;
printf("Char pointer start: %p\n", (void*)pChar);
printf("Char pointer + 1: %p\n", (void*)(pChar + 1));
// Result: Address increases by 1 byte
printf("Int pointer start: %p\n", (void*)pInt);
printf("Int pointer + 1: %p\n", (void*)(pInt + 1));
// Result: Address increases by 4 bytes (on most systems)
return 0;
}
The Invisible Multiplier
You can think of the math happening under the hood like this:
New Address = Current Address + (Index * Size of Data Type)
When you work with an int pointer, C treats ptr + 2 as ptr + (2 * 4 bytes). This automatic scaling is a massive helping hand; it allows you to navigate through arrays and memory structures without ever having to manually calculate byte offsets or remember the specific size of every data type on your system.
Key takeaway
Pointer arithmetic is type-aware: adding 1 moves the pointer forward by the number of bytes required to hold one instance of its specific data type.