You are here:

C/Structure padding and packing

Advertisement


Question
Hi,
I wants to know the difference between structure padding and packing.
Regs,
Tajinder

Answer
Structure padding is, adding extra bits at the end, so that the structure completes the word boundary.

Structure packing is, assigning only few bits to each of the structure members. This needs to use #pragma directive.
Some C compilers (especiallu GNU C) does not support the #pragma directives. In particular it does not support the "#pragma pack" directive. So when using the GNU C compiler, you can ensure structure packing in one of two ways

   * Define the structure appropriately so that it is intrinsically packed. This is hard to do and requires an understanding of how the compiler behaves with respect to alignment on the target machine. Also it is hard to maintain.
   * Use the "packed" attribute against the members of a structure. This attribute mechanism is an extension to the GNU C compiler. An example of how you would do this is below.

        struct sample
        {
            unsigned char  m1 __attribute__((__packed__));
            unsigned short m2 __attribute__((__packed__));
            unsigned long  m3 __attribute__((__packed__));
        };

     Another way to achieve the same is as shown below:

        struct sample
        {
            unsigned char  m1;
            unsigned short m2;
            unsigned long  m3;
        } __attribute__((__packed__));

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.