Possible Duplicate:
struct sizeof result not expected
Struct varies in memory size?
Here is the code compiled on Ubuntu Server 11.10 for i386 machine:
// sizeof.c
#include <stdio.h>
#include <malloc.h>
int main(int argc, char** argv){
printf("int's size: %d bytes\n", sizeof(int));
printf("double's size: %d bytes\n", sizeof(double));
printf("char's size: %d bytes\n", sizeof(char));
printf("\n");
printf("char pointer's size: %d\n", sizeof(char *));
printf("\n");
struct Stu{
int id;
char* name;
char grade;
char sex;
// double score;
};
printf("struct Stu's pointer's size : %d\n",sizeof(struct Stu *));
struct Stu stu;
stu.id=5;
stu.name="Archer";
stu.grade='A';
stu.sex='M';
printf("Stu(int,char*, char,char)'s size: %d bytes\n", sizeof(struct Stu));
printf("Stu(5,\"Archer\",'A','M')'s size: %d bytes\n",sizeof(stu));
}
compile:
`gcc -o sizeof sizeof.c`
output:
int's size: 4 bytes
double's size: 8 bytes
char's size: 1 bytes
char pointer's size: 4
struct Stu's pointer's size : 4
Stu(int,char*, char,char)'s size: 12 bytes
Stu(5,"Archer",'A','M')'s size: 12 bytes
My question is why the size of struct Stu
is 12, not sizeof(int) + sizeof(char *) + sizeof(char) + sizeof(char) = 4 + 4 + 1 + 1 = 10. When you put a double member into
struct Stu,
sizeof(struct Stu)` will be 20.