Phil CK

Size Changes Due Member Order

Last updated on

The compiler is free to add padding between the members of your structs, so a struct may at times sound bigger than you might expect.

#include <stdio.h>

struct foo {
        int a;
        short b;
        long c;
        char d;

struct bar {
        char a;
        short b;
        int c;
        long d;

struct baz {
        long a;
        int b;
        short c;
        char d;

main() {
        printf("sizeof(foo) %d\n", (int)sizeof(struct foo));
        printf("sizeof(bar) %d\n", (int)sizeof(struct bar));
        printf("sizeof(baz) %d\n", (int)sizeof(struct baz));

        return 0;

build and go

cc padding.c && ./a.out


sizeof(foo) 24
sizeof(bar) 16
sizeof(baz) 16

This is compiler dependent, I used clang on a macOS machine.