C and Sizeof question..

Vu Pham vu at sivell.com
Wed Nov 12 13:15:40 PST 2008


Steve Jardine wrote:
> Calling all C Gurus!!
> 
> Consider this C code:
> 
> #include <stdio.h>
> main() {
> 
> typedef struct {
> char           name[256];
> char           type[1]; 
> int             size;
> }resp;
> 
> char n[256];
> char t[1];
> 
> printf("sizeof resp is %d\n",sizeof(resp));
> printf("sizeof int is %d\n",sizeof(int));
> printf("Total: %d\n", sizeof(int)+sizeof(n)+sizeof(t));
> }
> 
> Can anyone explain why the sizeof the struct is 264 bytes, yet adding up all of its components yields 261 bytes?
> Call me confused...
> 

Use #pragma pack to inform the compiler to move all data structures 
"close" together.

This has some explanation:
http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/compiler/ref/rnpgpack.htm

Vu




More information about the Linux-users mailing list