为什么结构体的大小与其成员的总和不同?
如果我实现下面的代码,我的 sizeof(*zip) 输出是 56。 [10 + 10 + 4 + 4*8]byte = 56
typedef struct{
char a[10];
char b[10];
int c;
double d,f,g,h;
}abc_test;
abc_test zip[] =
{
{"Name" ,"Gender", 0,100,200,300,400},
{"Name" ,"Gender", 0,100,200,300,400}
};
但是当我实现下面的代码时,我的 sizeof(*zip) 输出是 440。 [100 + 100 + 100 + 100 + 4 + 4*8] = 436,我的问题是另一个4在哪里?
typedef struct{
char a[100];
char b[100];
char i[100];
char j[100];
int c;
double d,f,g,h;
}abc_test;
abc_test zip[] =
{
{"Name" ,"Gender","age","mode", 0,100,200,300,400},
{"Name" ,"Gender","age","mode", 0,100,200,300,400}
};
Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
If I implement below code, my output of sizeof(*zip) is 56.
[10 + 10 + 4 + 4*8]byte = 56
typedef struct{
char a[10];
char b[10];
int c;
double d,f,g,h;
}abc_test;
abc_test zip[] =
{
{"Name" ,"Gender", 0,100,200,300,400},
{"Name" ,"Gender", 0,100,200,300,400}
};
But when I implement below code, my output of sizeof(*zip) is 440.
[100 + 100 + 100 + 100 + 4 + 4*8] = 436, my question is where is another 4?
typedef struct{
char a[100];
char b[100];
char i[100];
char j[100];
int c;
double d,f,g,h;
}abc_test;
abc_test zip[] =
{
{"Name" ,"Gender","age","mode", 0,100,200,300,400},
{"Name" ,"Gender","age","mode", 0,100,200,300,400}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一般的答案是,编译器可以出于任何目的(通常是对齐要求)在成员之间自由添加填充。
具体答案是,您的编译器可能正在将
double
成员对齐到 8 字节边界。在第一个示例中不需要填充。在第二个示例中,在int c
成员之后需要 4 个字节的填充。The general answer is that compilers are free to add padding between members for whatever purpose (usually alignment requirements).
The specific answer is that your compiler is probably aligning the
double
members on an 8 byte boundary. In the first example that requires no padding. In the second example it requires 4 bytes of padding after theint c
member.您可能有一个编译器将所有内容都对齐到 8 字节。
You might have a compiler that aligns everything to 8 bytes.
AC 实现允许向结构体添加填充,以确保结构体的两个成员都针对目标平台进行最佳对齐,因此在形成结构体数组时,结构体本身的实例也是对齐的。
实现选择的特定对齐方式可能取决于特定结构的大小及其成员的类型和布局。
A C implementation is allowed to add padding to a struct to ensure that both the members of the struct are optimally aligned for the target platform and so the instances of the struct itself are aligned when an array of them is formed.
The particular alignment that the implementation chooses may depend on the size of a particular struct as well as the types and layout of its members.
如果你想让你的结构更有效地使用内存,请在它之前使用#pragma pack(push,1),然后使用#pragma pack(pop)。这将导致速度昂贵,并且可能在较小程度上影响代码大小。
请参阅http://www.cplusplus.com/forum/general/14659/
If you want to make your struct more memory efficient use #pragma pack(push,1) before it and #pragma pack(pop) afterwards. This will be at the expensive if speed, and possibly to a lesser extent, code size.
See http://www.cplusplus.com/forum/general/14659/