TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Bill Birrell
from: Darin McBride
date: 2003-08-09 09:41:26
subject: sizeof()

Hello Bill!

Replying to a message of Bill Birrell to Jasen Betts:

 BB> Hi Jasen,

 >> Given

 >> typedef struct moo
 >>   {
 >>  int foo;
 >>  char bar;
 >>   } moo;


 >> is   sizeof(moo) * 100   always the same as   sizeof(
 >> moo[100] )

 BB>     I think so. I'm not at all sure that moo[100] means anything at
 BB> all unless the array of structures is declared and consequently
 BB> storage is allocated.

Easy enough to check ...

#include 

typedef struct moo {
    int i;
    char c;
} moo;

int main()
{
    printf("sizeof(moo) * 100 = %d\nsizeof(moo[100]) = %d\n",
           sizeof(moo) * 100, sizeof(moo[100]));
    exit(0);
}

[0] f:\tmp\a>gcc a.c -o a.exe

[0] f:\tmp\a>a.exe
sizeof(moo) * 100 = 800
sizeof(moo[100]) = 800

 >> in other words does sizeof() include any slack space
 >> required for
 >> alignment.

I'm not sure if there is any requirement on the compiler to do this.  In
fact, I would doubt it.  Some platforms may decide to use that slack space
for other things if there is no performance impact.  Or if you give it a
pragma.  For example, with EMX (GCC for OS/2), if I add #pragma pack(1), I
get an output of 500 for both.

 BB>     Sizeof() returns the actual number of bytes of the dingus in the
 BB> brackets. Sizeof(moo) * 100 should return 300 with byte alignment.

Nope - with 16-bit ints, it would probably return 400 with byte alignment ;-)

 BB> The sizeof(an array of 100 structures of type moo) would also depend
 BB> on alignment. However unless you change alignment within the program
 BB> they should be the same.

Somehow, my copy of the ANSI C standard eludes me, so I can't even look
this up.  I suspect it's correct, but can't confirm... :-/

 BB>     This might be a dangerous assumption with modular compilation and
 BB> later linking unless you take care that all modules specify the same
 BB> alignment. I did come across this problem reading in and then
 BB> interpreting a data file compiled with PASCAL. In that case program
 BB> alignment had to match the data file.

 BB>     Darin McBride should be able to answer this off the top of his
 BB> head.

A bit much confidence, methinks.  ;-)

Darin

---
* Origin: Tanktalus' Tower BBS (1:250/102)
SEEN-BY: 633/267 270
@PATH: 250/102 99 10/345 106/1 2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.