Saturday, 17 August 2013

Why is offsetof(member) equal to sizeof(struct)?

Why is offsetof(member) equal to sizeof(struct)?

I have a struct defined as:
struct smth
{
char a;
int b[];
};
When I call sizeof and offsetof on this struct:
cout << sizeof(struct smth) << endl;
cout << offsetof(struct smth, val) << endl;
Output is:
4
4
How come when the size of the stuct is 4 and char is using 1 byte, the
offset of the int array is 4? Why is there some kind of padding? Also, why
isn't the second variable occupying any space at all (which seems like the
case)?

No comments:

Post a Comment