Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
sizeof(struct) returns unexpected value
I wrote a program to find the size of the following struct abc.
a. The inbuilt sizeof() operator mention the size of this struct to be 40 when it is actually 32? Also I tried subtracting the addresses to determine this and it also resulted in 40.
b. When I comment out "char g[3];" inside struct abc, the size of abc = 32. This also doesn't make any sense to me. Shouldn't this be 28?
c. Why do I need the casting to "unsigned int" ? If I do not do the casting, I get the following compilation error message. Isn't &a[0] actually an address (which should be an int)?
size_of_struct\size_of_struct.cpp(24): error C2440: '=' : cannot convert from 'abc *' to 'unsigned int'
Info: I am running win 7, 64 bit system. MS visual studio compiler.
#include <iostream>
struct char_three{
char a[3];
};
struct int_three{
int a[3];
};
struct abc
{
int a; // 4 bytes
double b; // 8
void *ptr; // 4
char g[3]; // 4 due to padding ?
int c[3]; // 12
}; // Total size of struct - 31 / 32.
int main ()
{
abc a[2];
unsigned int add0, add1;
add0 = (unsigned int) &a[0];
add1 = (unsigned int) &a[1];
printf("add1 of a is :%x add0 is :%x\n", add1, add0);
printf("size of struct abc : %d\n", add1-add0);
printf("size of int: %d\n", sizeof(int));
printf("size of double: %d\n", sizeof(double));
printf("size of void ptr: %d\n", sizeof(void *));
printf("size of 3 char: %d\n", sizeof(char_three));
printf("size of 3 int: %d\n", sizeof(int_three));
printf("size of a: %d\n", sizeof(a));
system("pause");
return 0;
}
O/P:
add1 of a is :51f828 add0 is :51f800
size of struct abc : 40
size of int: 4
size of double: 8
size of void ptr: 4
size of 3 char: 3
size of 3 int: 12
size of a: 80
Press any key to continue . . .