Home > Backend Development > C++ > 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?

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?

Linda Hamilton
Release: 2024-10-26 13:53:02
Original
657 people have browsed it

 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?

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>
Copy after login

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>
Copy after login

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:

    • Since all members are 2 bytes, the struct is aligned to a 2-byte boundary.
    • No padding is inserted between members, resulting in a total size of 6 bytes.
  • Second Struct:

    • The presence of a 4-byte int requires the struct to be aligned to a 4-byte boundary.
    • 2 bytes of padding are inserted between v3 and i to ensure proper alignment, bringing the total size to 12 bytes.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template