home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!mcsun!Germany.EU.net!Urmel.Informatik.RWTH-Aachen.DE!physik.tu-muenchen.de!berg
- From: berg@physik.tu-muenchen.de (Stephen R. van den Berg)
- Subject: Re: Memory alignment of struct elements
- Message-ID: <1992Aug13.131005.7040@Urmel.Informatik.RWTH-Aachen.DE>
- Originator: berg@tabaqui
- Sender: news@Urmel.Informatik.RWTH-Aachen.DE (Newsfiles Owner)
- Nntp-Posting-Host: tabaqui
- Organization: Rechnerbetrieb Informatik / RWTH Aachen
- References: <1992Aug12.133132.10723@Princeton.EDU>
- Date: Thu, 13 Aug 92 13:10:05 GMT
- Lines: 40
-
- >I am writing the software for a big database and the space is very
- >important. If I try to use a
-
- >struct { char ch ; float f }
-
- >the compiler (both in SunOS 4.0.1 and Interactive SYSVR3) allocates
- >8 bytes for it, starting the "f" element at fifth byte of the structure.
- >This makes both reading and writing such records from/to a binary database
- >file (consisting of 5-byte-long records) very inconvinient, requiring
- >a declaration of character array of 5 bytes and using "memcpy()". Is there
- >a way to force the compiler to align the struct elements following their
- >true length?
-
- What you should do in such a case, is to arrange all the elements in the
- struct in reverse size order. Of course, this order might be a bit compiler
- dependent, but you can make good guesses about it, and in your case, it
- will probably be portable to every machine you will ever need it on.
-
- So, declare the struct as:
-
- struct mystruct {float f;char ch;};
-
- And, for reading and writing this struct, use the following length:
-
- #define sizeof_mystruct (offsetof(struct mystruct,ch)+sizeof(char))
-
- Which will, most probably, be five on both architectures; do note however that
- the actual size of the struct will still be eight.
-
- This, of course, is only useable if you have the ability to reverse the order
- (i.e. the database file format is still changeable), and you don't try to
- read complete arrays from the database at once.
-
- In all other cases, using memcpy is inevitable, since alignment (e.g. on
- SPARCs) is not for the compiler to determine, it often is hardware dependent.
- --
- Sincerely, berg@pool.informatik.rwth-aachen.de
- Stephen R. van den Berg (AKA BuGless). berg@physik.tu-muenchen.de
-
- "Good moaning!"
-