← Back to C Course | Chapter 8: Structures & Unions | Lesson 7 of 7

C Struct Padding

Why Padding Exists

Most CPUs read multi-byte values fastest when they sit at a memory address that's a multiple of their own size -- a 4-byte int is fastest read from an address divisible by 4 -- so the compiler inserts unused padding bytes between struct members to keep each field aligned this way.

Example: Why Padding Exists

c
#include <stdio.h>
struct Example {
	char c;
	int i;
};
int main() {
	printf("%zu", sizeof(struct Example));
	return 0;
}

Seeing Padding with sizeof

A struct containing a char followed by an int often reports a sizeof larger than the sum of its members' individual sizes -- the compiler silently inserted 3 padding bytes after the char so the following int lands on a 4-byte boundary.

Example: Seeing Padding with sizeof

c
#include <stdio.h>
struct Mixed {
	char c;
	int i;
};
int main() {
	printf("%zu %zu %zu", sizeof(char), sizeof(int), sizeof(struct Mixed));
	return 0;
}

Field Order Affects Total Size

Reordering a struct's members can shrink or grow its total size even though the fields themselves haven't changed -- grouping larger types together and placing smaller ones like char at the end typically minimizes the padding the compiler needs to insert.

Example: Field Order Affects Total Size

c
#include <stdio.h>
struct Ordered {
	int i;
	char c;
};
struct Reordered {
	char c;
	int i;
};
int main() {
	printf("%zu %zu", sizeof(struct Ordered), sizeof(struct Reordered));
	return 0;
}

Padding at the End of a Struct

Compilers also add trailing padding after a struct's last member so that the struct's overall size is a multiple of its strictest member's alignment requirement, which matters when the struct is used inside an array so each element stays properly aligned.

Example: Padding at the End of a Struct

c
#include <stdio.h>
struct Trailing {
	int i;
	char c;
};
int main() {
	printf("%zu", sizeof(struct Trailing));
	return 0;
}

Disabling Padding When It Matters

Compiler-specific directives like #pragma pack(1) can force a struct to be packed with no padding at all, which matters when matching an exact binary file format or network protocol layout, but reading unaligned fields this way can be slower or even fault on some hardware.

Example: Disabling Padding When It Matters

c
#include <stdio.h>
#pragma pack(1)
struct Packed {
	char c;
	int i;
};
#pragma pack()
int main() {
	printf("%zu", sizeof(struct Packed));
	return 0;
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.