Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does int pointer '++' increment by 4 rather than 1?

Tags:

c++

c

pointers

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?

like image 961
Jason Avatar asked Apr 10 '11 07:04

Jason


2 Answers

When you increment a T*, it moves sizeof(T) bytes. This is because it doesn't make sense to move any other value: if I'm pointing at an int that's 4 bytes in size, for example, what would incrementing less than 4 leave me with? A partial int mixed with some other data: nonsensical.


Consider this in memory:

    [↓      ] [...|0 1 2 3|0 1 2 3|...] [...|int    |int    |...] 

Which makes more sense when I increment that pointer? This:

            [↓      ] [...|0 1 2 3|0 1 2 3|...] [...|int    |int    |...] 

Or this:

      [↓      ] [...|0 1 2 3|0 1 2 3|...] [...|int    |int    |...] 

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 of char is always one:

int i = 0; int* p = &i;  char* c = (char*)p; char x = c[1]; // one byte into an int 

†A corollary of this is that you cannot increment void*, because void is an incomplete type.

like image 132
GManNickG Avatar answered Oct 02 '22 09:10

GManNickG


Pointers are increased by the size of the type they point to, if the pointer points to char, pointer++ will increment pointer by 1, if it points to a 1234 bytes struct, pointer++ will increment the pointer by 1234.

This may be confusing first time you meet it, but actually it make a lot of sense, this is not a special processor feature, but the compiler calculates it during compilation, so when you write pointer+1 the compiler compiles it as pointer + sizeof(*pointer)

like image 23
MByD Avatar answered Oct 02 '22 10:10

MByD