Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

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

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
", ptr);
ptr++;
printf("%p
", ptr);

Expected output:

0xBF8D63B8
0xBF8D63B9

Actually output:

0xBF8D63B8
0xBF8D63BC

EDIT:

Another question - How to visit the 4 bytes an int occupies one by one?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...