Data alignment issues in C + +: struct, union, enum. Another talk about sizeof ()

Source: Internet
Author: User
Tags linux

The first is struct, in C + +, the structure actually and class have very much similarity. But one difference is that struct is public by default, and class is private.

Of course, the use of struct inheritance is also possible.

The common body is declared in the following ways:

The declaration of enumerations is similar to that of a common body

Where a is initialized to 0, followed by the default 1, if initialized, then add 1, such as d=6 here.

struct length calculation

Let's guess, S1 x;int b=sizeof (x);

What would his results be? Some people would think it should be 1+8+4+1=14.

is actually 24. Why is this so? This has a lot to do with the alignment of the structural body. Anyway, there are two.

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

1, the overall space is the largest number of bytes occupied by the integer times, such as the largest byte occupies a double, he is 8, it must be 8,16,24 ...

2. The memory is sorted according to the data member in the structure body, and the current address should be an integral multiple of the space occupied by the current member. For example, when double b occupies 8 bytes, the pendulum byte should be 8,16,24. While char A, with only one byte, the front space is automatically padded.

According to the two rules above, we are not difficult to draw 8+8+4+1, but should be 8 integer times, so it is 24.

Here it is necessary to add: in the LINUX+GCC environment, if the maximum member is 4, then the overall space is only a multiple of 4. So here's just a multiple of 4, 4,8,12,16,20,24.
2nd, in the LINUX+GCC environment, if a member type occupies more than 4 bytes, the front of the space only needs to be a multiple of 4. Double b in front, only 4 can be filled before, and no need to be padded 8.
Therefore, the overall space will be 20 of the situation. 4+8+4+1=17. But it should be a multiple of 4, then 20.

Related Article

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.