Why does int pointer #39;++#39; increment by 4 rather than 1?(为什么 int 指针 ++ 递增 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.
测试代码:
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.
这篇关于为什么 int 指针 '++' 递增 4 而不是 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 int 指针 '++' 递增 4 而不是 1?


- C++ 协变模板 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01