考虑以下
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"
&arr[0], 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",
&arr[0], 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
然而,它与我对内存地址和系统内存架构的推理方式相矛盾:
0x7ffe100ee500
C
int
变量是 4 字节大小,因此一个内存地址足以存储它(我想 0x7ffe100ee500
中剩余的 4 个字节会被忽略)。 ptr = ptr + 1
使指针的存储值(即内存地址0x7ffe100ee500
)向前移动4个字节。0x7ffe100ee501
即可。但是,我得到
0x7ffe100ee504
,就好像每个内存地址只包含 1 个字节。有人可以帮我理解吗?
我使用的是 64 位系统,这意味着每个内存地址存储 64 位,即 8 个字节。
错误。每个可寻址内存地址,根据定义,存储 1 个字节。拥有 64 位系统意味着地址是 64 位值。
因此,以 32 位
int
为例,其起始地址为 0x7ffe100ee500,该值占用地址 0x7ffe100ee500、0x7ffe100ee501、0x7ffe100ee502 和 0x7ffe100ee503。