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

2.3k Views Asked by At

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?

3

There are 3 best solutions below

6
On BEST ANSWER

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.

5
On

Because the size of the member b is zero, and the compiler adds padding between the a and b members so that b is on a "word" boundary.

However, if I remember correctly having a flexible array in a structure like that is only valid C, not C++ except as a compiler extension.

0
On

Since OP comments that the question is C++:

struct smth
{
    char a;
    int b[];
};

An array like b[] is invalid in C++. The array must have fixed size. Variable length arrays are only valid in C99.

Assuming that your compiler supports it as extension, the array b[] has a size of zero, which makes the struct containing only a char member. The the rule of padding in struct works, padding the struct to a word, which is 4 bytes in your machine.