Why is offsetof(member) equal to sizeof(struct)?
arrays, c++, offsetof, sizeof
Solution
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?
There is padding because the C standard allows it; the compiler often aligns variables to improve performance.
Also, why isn't the second variable occupying any space at all (which seems like the case)?
It's a C99 flexible array member - that's the entire point of it. The idea is to allocate your structure something like:
struct smth *s = malloc(sizeof *s + 10 * sizeof s->b[0]);
And then you'd have a structure that operates as if `b` were a 10-element array.
Problem
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, b) << 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 int array occupying any space at all?