[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Programming question: sizeof struct?

On Fri, 9 Jul 1999, Joop Stakenborg wrote:

> struct foo {
>     char text[3];
>     int  num;
> };
> sizeof would return 6 and not 5.  So it's obvious that the compiler is
> placing a pad byte between text and num to align num.  I want it to
> stop!

That's odd.  On most architectures, I would expect sizeof to result in at
least 7 because int's are at least four bytes long.

It is generally bad form to write code that, like this appears to do,
relies upon the rules of packing and alignment.  Of course, you didn't
write it so you're stuck with it, but such code is generally less portable
than doing things another way.

Coding up a simple example, I see that, without any options, the
sizeof(struct foo) results in 8.  Adding the -fpack-struct option, causes
the sizeof(struct foo) to result in 7.  Adding the line "#pragma pack(1)"
before the definition of the struct causes sizeof(struct foo) to result in
7.  This is with what I have installed (it says "egcs-2.91.60" on the
computer at the house, but I get identical results on an older system
running gcc

#include <stdlib.h>
#include <stdio.h>

struct foo {
  char text[3];
  int num;

main() {
  printf("sizeof(struct foo) = %d\n", sizeof(struct foo));
  return EXIT_SUCCESS;

I believe that, based upon your entire message, there are three possible
conclusions that can be reached about your difficulty.  1:  You may be
using an architecture where the char type (upon which the typedef is
based) is two or more bytes long.  2: You may be using a different C
compiler than I expect.  3:  You may be misinterpreting the output from
the compiler.  (Suppose "struct foo" is defined as you give it, but you're
actually looking at "sizeof(foo)" where foo is completely different.  That
sort of thing can drive you crazy.)
Jonathan Guthrie (jguthrie@brokersys.com)
Brokersys  +281-895-8101   http://www.brokersys.com/
12703 Veterans Memorial #106, Houston, TX  77014, USA

Reply to: