指针所存储的内存地址的增加不是应该取决于系统的架构吗?

问题描述 投票:0回答:1

考虑以下

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 字节大小,因此一个内存地址足以存储它(我想
    0x7ffe100ee500
    中剩余的 4 个字节会被忽略)。
  • 代码
    ptr = ptr + 1
    使指针的存储值(即内存地址
    0x7ffe100ee500
    )向前移动4个字节。
  • 由于每个内存地址最多可存储 8 个字节,因此将内存地址移至
    0x7ffe100ee501
    即可。

但是,我得到

0x7ffe100ee504
,就好像每个内存地址只包含 1 个字节。有人可以帮我理解吗?

c pointers memory architecture
1个回答
2
投票

我使用的是 64 位系统,这意味着每个内存地址存储 64 位,即 8 个字节。

错误。每个可寻址内存地址,根据定义,存储 1 个字节。拥有 64 位系统意味着地址是 64 位值。

因此,以 32 位

int
为例,其起始地址为 0x7ffe100ee500,该值占用地址 0x7ffe100ee500、0x7ffe100ee501、0x7ffe100ee502 和 0x7ffe100ee503。

© www.soinside.com 2019 - 2024. All rights reserved.