Summary of sizeof calculation in struct

Source: Internet
Author: User

Calculation of sizeof in struct

For example, struct exap



Double B;

Char C;

Double D;

Int E;

} Size;

Sizeof (struct exap) =? 40

TIPS: Method 1:

Short can only exist in multiples of 2

Double can only exist in 8 endorsements.

Char can only exist in multiples of 1

Int can only exist in multiples of 4

On this basis, data must be effectively aligned.

Method 2:

In VC, 8-byte alignment is specified. If the longest variable in struct is <8, it is calculated based on the longest byte alignment. If the longest variable in struct is> = 8, it is calculated in 8-byte alignment;

The optimization is performed in GCC, which requires 4-byte alignment. If the longest variable <4 in struct is calculated as the longest byte alignment, if the longest variable in struct is> = 4, it is calculated in 4-byte alignment;


Additionally, you can use # pragma pack () to modify the preceding rules. For example: # pragma pack (1), the above rule is changed to: 1) the offset must be a multiple of 1; 2) the number of bytes allocated to the object must be an integer multiple of 1.

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: 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.