Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 14 Mar 1999 20:31:44 -0500 (EST)
From:      Thomas David Rivers <rivers@dignus.com>
To:        ian@bulinfo.net, mturpin@saturn.spel.com
Cc:        freebsd-questions@FreeBSD.ORG
Subject:   Re: Programming Question
Message-ID:  <199903150131.UAA10509@lakes.dignus.com>
In-Reply-To: <36EC34C0.13D218B4@bulinfo.net>

next in thread | previous in thread | raw e-mail | index | archive | help
> Mark Turpin wrote:
> > 
> > I feel really silly having to ask this.
> > 
> > Why does my sizeof(mystruct) come out as 4 instead of 3 ( short + char ) ?
> > 
> >         struct {
> >            short        shortvariable;
> >            char         charvariable;
> >         } mystruct;
> > 
> >         sizeof(mystruct) == 4
> 
> Try finding the addresses of the structure members. As I know the compiler
> aligns every variable at even address. Maybe that's the reason.

 Not exactly... the size of the structure depends on the maximum alignment
 requirements of all of its members.

 In this case; on most architectures, the alignment of the `shortvariable'
 is 2, the alignment of `charvariable' is 1.   

 So, the alignment of the entire structure is 2.   The size of the
 structure is then padded - so that if you had an array of these structures,
 each array element would be properly aligned so that the structure
 alignment is preserved.   Thus, the size of the structure is padded to
 reach a two-byte alignment... adding one byte... making the size 4.

 That's why; when dealing with structures - the whole is typically greater
 than the sum of the parts... :-)

	- Dave Rivers -



To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199903150131.UAA10509>