Data Structure alignment, # pragma pack and _ attribute _ (packed ))

Source: Internet
Author: User

Gcc defines two statements for modifying the data structure alignment.

1. # pragma pack ()

2. _ attribute _ (packed ))

 

# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>

// Calculate the offset of t in S
# Define offsetof (S, t) (size_t) & (S *) 0)-> t)

Typedef struct _ S1 {
Char;
Char B;
Double c;
} S1;

// _ Attribute _ (packed) means no alignment optimization
Typedef struct _ S2 {
Char;
Char B;
Double c;
}__ Attribute _ (packed) S2;

Typedef struct _ Y
{
Int;
Int B;
Char C;
Char content [0];
} Y;

# Pragma pack (push, 4)
Struct A_4
{
Short V1;
Int V2;
};
# Pragma pack (POP)
# Pragma pack (push, 1)
Struct A_1
{
Short V1;
Int V2;
};
# Pragma pack (POP)

Int main ()
{

//The effect of _ attribute _ (packed), after _ attribute _ (packed) is used, no padding is available.


Printf ("/nsizeof (S1) = % u, offsetof (S1, c) = % u/N", sizeof (S1), offsetof (S1, c ));
Printf ("sizeof (S2) = % u, offsetof (S2, c) = % u/N", sizeof (S2), offsetof (S2, c ));
//This structure is very interesting. This structure Y is not optimized, so the compiler adds some padding to the end of this structure.

.

//So the size of this struct is 12, but the content offset is 9.


Printf ("sizeof (Y) = % u, offsetof (Y, content) = % u, offsetof (Y, c) = % u/n", sizeof (Y ), offsetof (Y, content), offsetof (Y, c ));

//One example of # pragma pack () directives


Printf ("sizeof (a_1) = % u/n", sizeof (struct a_1 ));
Printf ("sizeof (a_4) = % u/n", sizeof (struct a_4 ));
Getchar ();
Return 0;
}

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.