Size of struct NOT equal to the size of its content
Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
I have the next code:
http://ideone.com/brmRy
#include <stdio.h>
#include <stdlib.h>
typedef struct Test
{
int a;
int b;
char c;
} Test;
int main(void)
{
Test *obj = (Test*)malloc(sizeof(Test));
printf("Size results:rnrnstruct: %irnint #1: %irnint #2: %irnchar #1: %irn",
sizeof(Test), sizeof(obj->a), sizeof(obj->b), sizeof(obj->c));
return 0;
}
The result is:
Size results:
struct: 12
int #1: 4
int #2: 4
char #1: 1
Why DOES struct size 12 bytes??? int - 4 bytes char - 1 byte
2 int + 1 char = 2 * 4 bytes + 1 byte = 9 bytes.
Why does 12 ???
Memory is commonly aligned on 4-byte boundaries, so even though the char only takes up 1 byte, it's padded by 3 bytes to meet this segmentation requirement. Notably, individual elements of a struct don't have to be aligned, so if you made one of the ints into a short, you could reduce the struct size from 12 to 8 bytes. I believe you'd have to put the short next to the char in the struct declaration to receive this bonus, though.
If you're using gcc you can force "packing". This means that no nalignment is made and the struct entries stand next to each other. Try
typedef struct Test
{
int a;
int b;
char c;
} __attribute__((packed)) Test;
链接地址: http://www.djcxy.com/p/80210.html
上一篇: printf()是否在C中分配内存?
下一篇: 结构的大小不等于其内容的大小