为什么&打印结束位置的内存地址

时间:2019-01-21 09:24:03

标签: c

据我所知,结构元素存储在连续的存储单元中。为了确认这一点,我在下面的示例应用程序中进行了编写。

#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 个答案:

答案 0 :(得分:2)

这可能是由于padding bytes造成的。正如您所说,结构确实存储在连续的内存位置中,但是,编译器可以随意在元素之间添加填充字节,无论它们选择什么,它们都会这样做,以使字段与体系结构自然对齐。通常,只有自然对齐的由多个字节组成的单词才能由单个指令访问。

答案 1 :(得分:1)

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

此外,这篇文章对于理解结构填充也很有用:Structure padding and packing

相关问题