为什么 int 指针 '++' 递增 4 而不是 1?

2021-12-13 00:00:00 pointers c c++

指针的值是变量的地址.为什么 int 指针的值在 int 指针增加 1 后增加了 4 个字节.

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.

在我看来,我认为指针(变量地址)的值在指针增加后只会增加 1 个字节.

In my opinion, I think value of pointer(address of variable) only increase by 1-byte after pointer increment.

测试代码:

int a = 1, *ptr;
ptr = &a;
printf("%p
", ptr);
ptr++;
printf("%p
", ptr);

预期输出:

0xBF8D63B8
0xBF8D63B9

实际输出:

0xBF8D63B8
0xBF8D63BC

编辑:

再问一个int占用的4个字节如何一一访问?

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

推荐答案

当你增加一个 T* 时,它移动 sizeof(T) 个字节.? 这是因为移动任何其他值都没有意义:例如,如果我指向一个大小为 4 个字节的 int,那么增量小于 4 会留下什么跟我?与一些其他数据混合的部分 int:无意义.

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.

在内存中考虑:

    [↓      ]
[...|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    |...]

或者这个:

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

最后一个实际上并不指向任何类型的 int.(从技术上讲,使用该指针是 UB.)

The last doesn't actually point an any sort of int. (Technically, then, using that pointer is UB.)

如果你真的想移动一个字节,增加一个char*:char的大小总是一:

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

<小时>

?一个推论是你不能增加 void*,因为 void 是一个不完整的类型.


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

相关文章