代码之家  ›  专栏  ›  技术社区  ›  Hari Krishna

为什么内存地址的打印结束位置为[重复]

c
  •  0
  • Hari Krishna  · 技术社区  · 7 年前

    如我所知,strucure元素存储在连续的内存位置中。为了证实这一点,我在下面写了一份申请样本。

    #include <stdio.h>
    
    struct Employee{
        char firstName;
        float salary;
        int id;
    };
    
    
    int main(){
    
        struct Employee emp = {'K', 123456.78, 1};
    
        printf("firstName stored at location : %lu\n", &emp.firstName);
        printf("salary stored at location : %lu\n", &emp.salary);
        printf("id stored at location : %lu\n", &emp.id);
    
        return 0;
    }
    

    当我运行应用程序时,我看到下面的输出类型。

    firstName stored at location : 140732780083504
    salary stored at location : 140732780083508
    id stored at location : 140732780083512
    

    正如您看到的输出,firstname存储在140732780083504位置,薪金存储在140732780083508位置,难道薪金不能是140732780083505吗?它总是返回特定变量的结束位置。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Gamification    7 年前

    这可能是由于 padding bytes .正如您所说,结构存储在连续的内存位置是有点正确的,但是编译器可以自由地在元素之间添加填充字节,不管它们是如何选择的,它们这样做是为了使字段与架构自然对齐。由多个字节组成的字通常只有在自然对齐的情况下才能被一条指令访问。

        2
  •  1
  •   Denis Sablukov    7 年前

    发生这种情况是因为编译器的默认结构填充为4字节。 如果希望结构元素在内存中一个接一个使用 #pragma pack(push, 1)

    此外,本帖还可帮助理解结构填充: Structure padding and packing