为什么4而不是1呢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.
测试code:
int a = 1, *ptr;
ptr = &a;
printf("0x%X\n", ptr);
ptr++;
printf("0x%X\n", ptr);
期望的输出:
0xBF8D63B8
0xBF8D63B9
实际输出的:
0xBF8D63B8
0xBF8D63BC
修改
另外一个问题 - 如何一个参观4个字节的 INT
占用一个
Another question - How to visit the 4 bytes an int
occupies one by one?
当你增加一个 T *
,它移动的sizeof(T)
字节†这是因为它没有任何意义,以移动任何其他值:如果我指着一个 INT
这是4字节大小,例如,你会递增不到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 *
:的字符大小code>总是之一:
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.