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?
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- c++ STL设置差异 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
