Memory Alignment in C Structures
In computing, memory alignment refers to the restrictions placed on the addresses at which data can be stored in memory. Understanding memory alignment is crucial for optimizing code performance and avoiding unexpected behavior.
Problem Statement:
You're working on a 32-bit system where memory alignment is typically set to 4 bytes. Consider the following struct:
<code class="c">typedef struct { unsigned short v1; unsigned short v2; unsigned short v3; } myStruct;</code>
The struct contains three 2-byte fields, but using the sizeof operator returns 6 bytes instead of the expected 8 bytes. Conversely, the following struct:
<code class="c">typedef struct { unsigned short v1; unsigned short v2; unsigned short v3; int i; } myStruct;</code>
returns a size of 12 bytes, as expected from the increased number of fields and the potential for padding. Why is there a difference in the resulting sizes?
Explanation:
On most machines, data types are aligned to a boundary no larger than their size. In this case, short is 2 bytes, and int is 4 bytes.
First Struct:
Second Struct:
The above is the detailed content of Why Does a C Structure with 3 Short Integers Have a Size of 6 Bytes, But a Similar Structure with an Integer Added Has a Size of 12 Bytes?. For more information, please follow other related articles on the PHP Chinese website!