structure-packing

size of struct in C [duplicate]

允我心安 提交于 2019-11-26 19:11:39
问题 This question already has answers here : Closed 9 years ago . Possible Duplicate: Why isn’t sizeof for a struct equal to the sum of sizeof of each member? Consider the following C code: #include <stdio.h> struct employee { int id; char name[30]; }; int main() { struct employee e1; printf("%d %d %d", sizeof(e1.id), sizeof(e1.name), sizeof(e1)); return(0); } The output is: 4 30 36 Why is the size of the structure not equal to the sum of the sizes of its individual component variables? 回答1: The

Memory alignment in C-structs

蓝咒 提交于 2019-11-26 18:31:21
I'm working on the 32-bit machine, so I suppose that memory alignment should be 4 bytes. Say I have struct: typedef struct { unsigned short v1; unsigned short v2; unsigned short v3; } myStruct; the real size is 6 bytes, and I suppose that aligned size should be 8, but sizeof(myStruct) returns me 6. However if I write: typedef struct { unsigned short v1; unsigned short v2; unsigned short v3; int i; } myStruct; the real size is 10 bytes, aligned is 12, and this time sizeof(myStruct) == 12 . Can somebody explain what is the difference? Jerry Coffin At least on most machines, a type is only ever