C and Sizeof question..
Roger Oberholtzer
roger at opq.se
Sun Nov 16 23:49:19 PST 2008
On Wed, 2008-11-12 at 19:33 +0000, 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...
Try this:
#include <stdio.h>
main() {
# pragma pack(1)
typedef struct {
char name[256];
char type[1];
int size;
}resp;
char n[256];
char t[1];
# pragma pack(4)
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));
}
We use this pragma when defining structures that will be sent to other
machine architectures.
--
Roger Oberholtzer
OPQ Systems / Ramböll RST
Ramböll Sverige AB
Krukmakargatan 21
P.O. Box 17009
SE-104 62 Stockholm, Sweden
Office: Int +46 8-615 60 20
Mobile: Int +46 70-815 1696
--
"On two occasions I have been asked (by members of Parliament!),
'Pray, Mr. Babbage, if you put into the machine wrong figures,
will the right answers come out?' I am not able rightly to apprehend
the kind of confusion of ideas that could provoke such a question.
- Charles Babbage 1791-1871)
English computer pioneer, philosopher
And remember:
It is RSofT and there is always something under construction.
It is like talking about large city with all constructions finished.
Not impossible, but very unlikely.
More information about the Linux-users
mailing list