Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Alignment and Padding in Structs | Understanding Structs and Memory
C Structs

bookAlignment and Padding in Structs

メニューを表示するにはスワイプしてください

Alignment

Each structure field is aligned to a boundary that is a multiple of the size of the structure's largest element.

For example, if the largest element is 4 bytes in size, then each element will be aligned on a 4-byte boundary.

This is done to speed up memory access and avoid hardware alignment problems.

main.c

main.c

copy
1234567891011121314151617181920
#include <stdio.h> // simple struct struct Example { char a; int b; double c; }; int main() { struct Example test; printf("Size of struct Example: %zu\n", sizeof(test)); printf("Address of test.x (char): %p\n", &test.a); printf("Address of test.y (int): %p\n", &test.b); printf("Address of test.c (double): %p\n", &test.c); return 0; }

You might be wondering why the size of struct Example is 16 bytes, even though each field is aligned to the boundary of the largest type, which is 8 bytes. At first glance, aligning all three fields to 8 bytes might suggest a total size of 24 bytes. In reality, it works a bit differently.

The first field a is a char and takes up 1 byte. To make sure the next field b of type int starts at a 4-byte boundary, the compiler adds 3 bytes of padding after a. The field b itself takes 4 bytes and is now properly aligned.

The next field c is a double and needs to start at an 8-byte boundary. The compiler adds padding after b to place c at the correct address. The field c occupies 8 bytes.

In total: 1 byte for a + 3 bytes padding + 4 bytes for b + 8 bytes for c = 16 bytes. The alignment rules are followed, and memory is used efficiently.

question mark

Why does the size of a struct often exceed the sum of the sizes of its individual fields?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  2
some-alt