Struct byte alignment (excluding discussion about struct nesting and modifying the alignment of machines). For more details, see add to favorites.

Source: Internet
Author: User

Byte alignment:

1. The offset from the first address must be an integer multiple of the variable length.

2. the variables are stored in the defined order.

3. The length of the entire struct must be an integer multiple of the length of the longest member variable.

4 If struct is nested, the variables in the sub-struct must comply with the preceding three principles throughout the entire struct, but the storage location of each variable in the sub-struct itself will not change.

E.g.

Struct nssb {
Long;
Short B;
Char C;
Short D;
Char ch [3];
} OBJ, * P;

Cout <"sizeof long" <sizeof (long) <Endl;
Cout <"sizeof double" <sizeof (double) <Endl;
Cout <"sizeof float" <sizeof (float) <Endl;
Cout <"sizeof int" <sizeof (INT) <Endl;
Cout <"sizeof short" <sizeof (short) <Endl;
Cout <"sizeof char" <sizeof (char) <Endl;
Cout <"sizeof P" <sizeof (p) <Endl;
Cout <"sizeof * P" <sizeof (* P) <Endl;

P = (struct nssb x *) 0x1000000;
// Cout <"next struct is" <(p + 0x1) <Endl;
// Obj. c = 'C ';
Cout <"A" <& obj. A <Endl;
Cout <"B" <& obj. B <Endl;
Cout <"C" <& obj. C <Endl;
Cout <"D" <& obj. d <Endl;
Cout <"ch" <& obj. ch <Endl;

 

Running result:

[Root @ 127 test] #./test. x
Sizeof long 4
Sizeof double 8
Sizeof float 4
Sizeof int 4
Sizeof short 2
Sizeof char 1
Sizeof P 4
Sizeof * P 16
A 0xbfcee3c0
B 0xbfcee3c4
C d.
D 0xbfcee3c8
Ch 0xbfcee3ca

 

 

 

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.