考虑以下内容
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
然而,这与我对内存地址和系统内存架构的推理方式相矛盾:
-
我使用的是64位系统,这意味着每个内存地址存储64位,或者相当于8个字节。
-
我的第一个整数元素数组的内存地址是
0x7ffe100ee500
-
由于每个内存地址最多可存储8个字节
C
int
变量大小为4字节,一个内存地址就足以存储它(我想剩下的4个字节
0x7ffe100ee500
被简单地忽略)。
-
代码
ptr = ptr + 1
使指针的存储值(即,内存地址
0x7ffe100ee500
)向前移动4个字节。
-
由于每个存储器地址最多可存储8个字节,因此将存储器地址移位到
0x7ffe100ee501
就足够了。
然而,我得到了
0x7ffe100ee504
,就好像每个存储器地址只包含1个字节。有人能帮我理解一下吗?