C语言 指针存储地址的增加不应该依赖于系统的体系结构吗?

chy5wohz  于 2023-10-16  发布在  其他
关注(0)|答案(1)|浏览(70)

考虑以下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个字节,而我的Cint变量是4个字节,一个内存地址就足以存储它(我假设0x7ffe100ee500中剩下的4个字节被忽略了)。
  • 代码ptr = ptr + 1使指针的存储值(即存储器地址0x7ffe100ee500)向前移动4个字节。
  • 由于每个内存地址最多存储8个字节,因此将内存地址移位到0x7ffe100ee501就足够了。

然而,我得到了0x7ffe100ee504,好像每个内存地址只包含1个字节。有没有人能给予给我一个帮助来理解它?

hfyxw5xn

hfyxw5xn1#

我在一个64位系统上,这意味着每个内存地址存储64位,或相当于8个字节。
每个可寻址内存地址,* 根据定义 *,存储1个字节。具有64位系统意味着地址是64位值。
因此,以32位int为例,其起始地址为0x7ffe100ee500,该值占用地址0x7ffe100ee500、0x7ffe100ee501、0x7ffe100ee502和0x7ffe100ee503。

相关问题