LunchMarble
LunchMarble

Reputation: 5141

Understanding the size of my structure

My code:

typedef struct {
    int sizeOfMyIntArray;
    int* myIntArray;
    float someFloat;
} my_struct_foo;

int main() {
    printf("The size of float is: %d\n", sizeof(float));
    printf("The size of int is: %d\n", sizeof(int));
    printf("The size of int* is: %d\n", sizeof(int*));
    printf("The size of my_struct_foo is: %d\n", sizeof(my_struct_foo));
    return 0;
}

I'd imagine that this is very simple. Although, I am a bit surprised by the resulting output of this program...

The size of float is: 4
The size of int is: 4
The size of int* is: 8
The size of my_struct_foo is: 24

I have one float, one int, and one pointer-to-an-int. In my head I am thinking: 4 + 4 + 8 = 16...not 24. Why is the size of my structure 24 instead of 16?

Upvotes: 3

Views: 115

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183888

Alignment and padding. The int* should be aligned on an eight-byte boundary, so the compiler inserts four bytes of padding between the int and the pointer, and after (or before) the float to make the size of the struct a multiple of the pointer size and have the pointer correctly aligned.

If you reorder the members,

typedef struct {
    int sizeOfMyIntArray;
    float someFloat;
    int* myIntArray;
} my_struct_foo;

the pointer would be correctly aligned without any padding, so the size of the struct would (very probably, the compiler is allowed to add padding even if it is not needed, but I know of none that does) be 16.

Upvotes: 2

Related Questions