C Programming help .....wtf ?!?!

Kurt Wall kwall
Tue Jan 25 20:25:41 PST 2005


On Tuesday 25 January 2005 15:16, Ben Duncan wrote:
> Why does the sizeof( struct _dummymenu) on the below
> return 8 ?

Alignment purposes. The compiler will pad the structure to maintain 
natural alignment. 

>    typedef struct _dummymenu
>         {
>         char d_char ;

1 byte

>         int d_sumnumber ;

4 bytes

>         } DummyMenu ;

GCC adds three bytes to maintain alignment on a word boundary.

>
> Yet if I do one a structure like this:
>
> typedef struct _dummymenu
>         {
>         char a_char ;
>         char b_char ;
>         char c_char ;
>         } DummyMenu ;
>
> it returns 3 ......

Because it's already aligned. If you don't want the padding, use the 
((packed)) attribute:

#include <stdio.h>

int main(void)
{
 typedef struct __attribute__ ((packed)) _a {
  char c;
  int i;
 } _a;
 _a A;

 printf("sizeof(A) = %d\n", sizeof(A));
 printf("sizeof(A.c) = %d\n", sizeof(A.c));
 printf("sizeof(A.i) = %d\n", sizeof(A.i));

 return 0;
}
  
With the ((packed)) attribute, sizeof() reports 5 bytes:
sizeof(A) = 5
sizeof(A.c) = 1
sizeof(A.i) = 4

See also the -Wpadded and -Wpacked command-line arguments to GCC. I seem 
to recall some guy wrote a book about this stuff...

Kurt


More information about the Linux-users mailing list