Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!psuvax1!psuvm!cmh117 From: CMH117@psuvm.psu.edu (Charles Hannum) Newsgroups: comp.lang.c Subject: Re: Memory allocation of structures Message-ID: <90064.170124CMH117@psuvm.psu.edu> Date: 5 Mar 90 22:01:24 GMT References: <1457@navy8.UUCP> Distribution: usa Organization: Penn State University Lines: 48 In article <1457@navy8.UUCP>, kreidler@cell.mot.COM (Joe Kreidler) says: > > ... > >Is there some reason for structures being allocated memory as I described >above? Is this observation part of the ANSI standard? Any insights are >appreciated. Yes, there are two very good reasons for this. Consider the following: struct { short a, b, c; } foo; typedef struct { int d; short 8-bit short e; int 16-bit } bar; bar foobar[] = {{0,1},{2,3},{3,4},{4,5}}; There are several problems with this: 1) bar must be word-aligned! Try accessing a 16-bit integer on an odd boundary on a PDP-11 (or an 80x86, where it takes twice as long as if the int was at an even address)! Okay, so maybe the *beginning* of a struct should be word-aligned. This brings us to ... 2) What if I want to use (sizeof(foobar)/sizeof(bar)) to determine the number of elements in bar? Here's what I'd get: (3+1+3+1+3+1+3)/3 = 15/3 = 5 (The 1s represent the word-alignment of the elements in foobar.) This obviously not correct. The only solution to this problem is to make the *end* of the structure word-aligned, in which case neither of these problems occur. Virtually, - Charles Martin Hannum II "Klein bottle for sale ... inquire within." (That's Charles to you!) "To life immortal!" cmh117@psuvm.{bitnet,psu.edu} "No noozzzz izzz netzzzsnoozzzzz..." c9h@psuecl.{bitnet,psu.edu} "Mem'ry, all alone in the moonlight ..."