代码之家  ›  专栏  ›  技术社区  ›  Rubem Pacelli

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

  •  0
  • Rubem Pacelli  · 技术社区  · 2 年前

    考虑以下内容 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个字节。有人能帮我理解一下吗?

    1 回复  |  直到 2 年前
        1
  •  5
  •   dbush    2 年前

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

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

    举个32位的例子 int 其起始地址为0x7ffe100ee500,该值占用地址0x7ffe100 ee500、0x7ffe 100ee501、0x7 ffe 100ee 502和0x7 ffe100 ee503。