为何C语言int指针+1偏移4字节?求解64位系统内存认知误区
64位系统中C语言指针偏移的逻辑解释
运行的C代码
#include <stdio.h> int main() { int arr[] = {10, 20, 30, 40}; int *ptr = arr; // ptr points to the internal pointer variable of `arr`, that is, the address of its first array element, 10. printf("The address of the first int array element is : %p\n" "The stored value (.i.e., the memory address) of the pointer is: %p\n", (void*)&arr[0], (void*)ptr); printf("The memory size the a int variable is: %zu bytes, which is equal to %lu bits (each byte has 8 bits).\n" "Since `ptr` is a int pointer, the command `ptr = ptr + 1` shifts stored memory address of `ptr` in %zu bytes.\n\n", sizeof(int), 8*sizeof(int), sizeof(int)); ptr = ptr + 1; // Move ptr to the memory address of the next integer (20) (instead, you could use `ptr++`) printf("The address of the first int array element is : %p\n" "The stored value (.i.e., the memory address) of the pointer is: %p\n\n", (void*)&arr[0], (void*)ptr); return 0; }
代码输出结果
The address of the first int array element is : 0x7ffe100ee500 The store value (.i.e., the memory address) of the pointer is: 0x7ffe100ee500 The memory size the a int variable is: 4 bytes, which is equal to 32 bits (each byte has 8 bits). Since `ptr` is a int pointer, the command `ptr = ptr + 1` shifts stored memory address of `ptr` in 4 bytes. The address of the first int array element is : 0x7ffe100ee500 The store value (.i.e., the memory address) of the pointer is: 0x7ffe100ee504
用户的认知矛盾
- 64位系统中每个内存地址对应8字节(64位)存储单元;
- C语言int变量仅占4字节,单个内存地址即可容纳;
- 认为指针执行
ptr = ptr + 1只需偏移1字节(即一个地址)就能指向后续int变量,而非4字节。
逻辑解释
首先纠正一个关键误解:内存地址指向的是单个字节的位置,而非8字节单元。64位系统指的是CPU寄存器宽度、内存地址的长度为64位(可寻址2^64个字节),但每个地址对应的是1字节的存储空间,不是8字节。
C语言中指针的算术运算遵循**“类型感知”规则**:对指针执行+1操作时,偏移的字节数等于指针指向类型的大小,而非固定1字节。这是C语言为简化数组操作设计的特性——数组在内存中是连续存储的同类型元素,ptr + n会直接指向当前位置后的第n个元素,无需手动计算字节偏移。
回到你的例子:
int类型占4字节,数组arr在内存中连续排列:10占用0x7ffe100ee5000x7ffe100ee503,`20`占用0x7ffe100ee5040x7ffe100ee507,以此类推。ptr是int*类型,ptr + 1会自动偏移sizeof(int)(即4字节),直接指向数组的下一个int元素,也就是20的起始地址0x7ffe100ee504,与输出结果完全一致。
你之前的错误在于混淆了“内存地址的长度(64位)”和“地址指向的存储单元大小(1字节)”——64位地址只是用来标记每个字节的位置,每个地址对应1字节,而非8字节。因此要跳到下一个int元素,必须偏移4个字节(4个地址位置),而非1个字节。
内容的提问来源于stack exchange,提问作者user13343959
相关产品推荐
相关产品推荐

