Value of a pointer is address of a variable. Why value of an int pointer increased by 4-bytes after the int pointer increased by 1.
In my opinion, I think value of pointer(address of variable) only increase by 1-byte after pointer increment.
Test code:
int a = 1, *ptr;
ptr = &a;
printf("%p\n", ptr);
ptr++;
printf("%p\n", ptr);
Expected output:
0xBF8D63B8
0xBF8D63B9
Actually output:
0xBF8D63B8
0xBF8D63BC
EDIT:
Another question – How to visit the 4 bytes an int occupies one by one?
When you increment a
T*, it movessizeof(T)bytes.† This is because it doesn’t make sense to move any other value: if I’m pointing at anintthat’s 4 bytes in size, for example, what would incrementing less than 4 leave me with? A partialintmixed with some other data: nonsensical.Consider this in memory:
Which makes more sense when I increment that pointer? This:
Or this:
The last doesn’t actually point an any sort of
int. (Technically, then, using that pointer is UB.)If you really want to move one byte, increment a
char*: the size of ofcharis always one:†A corollary of this is that you cannot increment
void*, becausevoidis an incomplete type.