Path: utzoo!mnetor!tmsoft!torsqnt!news-server.csri.toronto.edu!bonnie.concordia.ca!clyde.concordia.ca!nstn.ns.ca!news.cs.indiana.edu!att!linac!pacific.mps.ohio-state.edu!zaphod.mps.ohio-state.edu!mips!batman From: sah@batman (Steve Hanson) Newsgroups: comp.sys.mips Subject: Re: Unaligned struct access (how to) Message-ID: <45928@mips.mips.COM> Date: 14 Feb 91 23:01:55 GMT References: <5054@lure.latrobe.edu.au> Sender: news@mips.COM Reply-To: sah@batman (Steve Hanson) Organization: MIPS Computer Systems Inc. Lines: 78 In-reply-to: CCHD@lure.latrobe.edu.au (Huw Davies - La Trobe University Computer Centre) In article <5054@lure.latrobe.edu.au>, CCHD@lure (Huw Davies - La Trobe University Computer Centre) writes: >I have a slight problem with the c compiler (on MIPS 120/5 running RISC/os >4.5.1). > >The following code doesn't do what I want :-) Please note that this >is an example of the error extracted from debugging 6K lines of c code >(It took a while to find....). > >$ more test_struct.c >#include > >struct test >{ > short a; > int b; >} c; > >main() >{ > printf("a: %x\nb: %x\nSize of a: %d\n", &c.a, &c.b, > (int) &c.b - (int) &c.a); >} > >$ ./test >a: 2003e460 >b: 2003e464 >Size of a: 4 >$ > >I would have liked the difference in address to be 2, not 4. I know >that there are efficiency reasons for aligned access, but I would like >to be able to override the default. > >For those few of you who read comp.unix.aix as well (there's got to be >someone else who believes in vendor independence...) I have the >same problem with our RS/6000 systems. (Different implementation - same >bugs :-) > >Huw Davies >Computing Services > >e-mail: cchd@lucifer.latrobe.edu.au Taken from the 2.20, in Beta now, release notes: o #pragma pack(n) #pragma pack() The first form is used to change the strictest alignment of structure members within a structure. n is the new alignment restriction in bytes. If n is omitted, then it defaults to the compiler option -Zp, if present, or the compiler default, which is the strictest member alignment. Your code would look like: #include #pragma pack(2) struct test { short a; int b; } c; main() { printf("a: %x\nb: %x\nSize of a: %d\n", &c.a, &c.b, (int) &c.b - (int) &c.a); } with the ouput: a: 10000b7c b: 10000b7e Size of a: 2