C ++ efficient programming NOTE 2: byte alignment in struct

Source: Internet
Author: User

# Include <iostream. h>

struct A {
char A ; long B ; char C ; long d ;
};
struct B {
char A ; char C ; long B ; long d ;
};

# Pragma pack (push, 1)
StructC{
CharA;LongB;CharC;LongD;
};
# Pragma pack (POP)

Struct D {
Char * A ; Char * B ;
};
// Use the structure of the bit domain
Struct Bitfield {
Unsigned A1 : 11 ; // Long 1
Unsigned A2 : 11 ;
Unsigned B1 : 10 ;
Unsigned A3 : 11 ; // Long 2
Unsigned A4 : 11 ;
Unsigned B2 : 10 ;
};

Void Main ( Void )
{
Cout < "Size of :" < Sizeof ( A ) < "Bytes" < Endl ;
Cout < "Size of B :" < Sizeof ( B ) < "Bytes" < Endl ;
Cout < "Size of C :" < Sizeof ( C ) < "Bytes" < Endl ;
Cout < "Size of D :" < Sizeof ( D ) < "Bytes" < Endl ;
Cout < "Size of bitfield :" < Sizeof ( Bitfield ) < "Bytes" < Endl ;
}

 

Running result:

Size of A: 16 bytes
Size of B: 12 bytes
Size of C: 10 bytes
Size of D: 8 bytes
Size of bitfield: 8 bytes
The reason why A, B, and C are different is byte alignment. # The Pragma pack (push, 1) command allows the compiler to temporarily adjust the alignment to 1 byte.
Note that char * generally occupies 4 bytes.

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.