Alignment of variable storage in structures in C Language

Source: Internet
Author: User

In C, the Declaration Order of the variables in the struct varies with the bytes.

For example,

 
Struct {short X; long y; char Z;};

The preceding struct occupies 12 bytes.


 
Struct {short X; char y; long Z;} B;

This struct occupies 8 bytes.


The reason is that the compiler has alignment problems.

In the first struct a, X occupies 2 bytes, but y occupies 4 bytes. It cannot be directly supplemented after the space in X. In order to align y with X, the second byte after the space occupied by X is wasted and not used. Z occupies 4 bytes to maintain alignment. A total of 12 bytes.

In the second struct B, X occupies 2 bytes, and y occupies 1 byte. According to the alignment principle, the next byte of Y occupies is wasted. The remaining variable z occupies 4 bytes. A total of 8 bytes.

The following figure shows how

Shows the space occupied by the first struct a. Black represents the bytes that store the data, and red represents the bytes that do not store the data.



Shows the space occupied by the second struct B,Black indicates the bytes of the stored data, and red indicates the bytes of the data that are not stored.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.