Cross-platform discussion of union and struct type sizes

Source: Internet
Author: User

This question of the textbook online a lot, I will not say more here to give a: Click to open the link

This question is the most likely to cause a dispute, why? With the platform or the compiler has a relationship, first look at the following code:

#include <iostream>using namespace std;union u1{    char a[9];    int b;}; Union u2{    U1 A;    Double b;}; Union u3{    Char a[10];    Double b;}; struct s1{    char a[13];    Double C;}; struct s2{    S1 A;    U1 b;}; struct s3{    char b;    int C;    Char d[13];}; int main () {    cout << "U1:" << sizeof (U1) << Endl;    cout << "U2:" << sizeof (U2) << Endl;    cout << "U3:" << sizeof (U3) << Endl;    cout << "S1:" << sizeof (S1) << Endl;    cout << "S2:" << sizeof (S2) << Endl;    cout << "S3:" << sizeof (S3) << Endl;    return 0;}
I tested it in two ways, with the following results:

(1) The results of the g++ compilation under Ubuntu system are as follows:


(2) Under Windows System, the results of CMake compilation are as follows:


Specifically not very clear, may be Ubuntu did some optimization, welcome to discuss

Cross-platform discussion of union and struct type sizes

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.