Path: utzoo!attcan!uunet!ogicse!ucsd!ucbvax!bloom-beacon!daemon From: scs@adam.mit.edu (Steve Summit) Newsgroups: comp.lang.c Subject: Re: sizeof(struct) and padding Message-ID: <1990Oct20.003222.25439@athena.mit.edu> Date: 20 Oct 90 00:32:22 GMT References: <1229@sun13.scri.fsu.edu> Sender: daemon@athena.mit.edu (Mr Background) Reply-To: scs@adam.mit.edu (Steve Summit) Organization: Thermal Technologies, Inc. Lines: 47 In article <1229@sun13.scri.fsu.edu> mayne@sun10.scri.fsu.edu (William (Bill) Mayne) writes: [sizeof() reflects padding at ends of structures.] >"Big deal!" you say? Actually it could make an important differnce >if the structure is being written as a record to a file. Then extra >file space will be used. >The $64K question is: How do I portably get the actual size of >a structure without padding when I need that rather than >what sizeof() tells me? My $64,000 question is: why are so many poor souls condemned to try to read and write binary data files? Yes, it is easy and quick to use fwrite and sizeof to write whole structs to a file, but those are the only two good things which can be said about it. Binary files are otherwise quite difficult to work with, not to mention unportable, sometimes even to the same machine on which they were written. More flexible (e.g. text) file formats offer hosts of advantages, and can be implemented reasonably easily and efficiently as well. (This debate appears here endlessly, and I should add it to the FAQ if I could think of a succinct way. I won't repeat all the pros and cons right now.) If a binary format has not already been forced upon you by some prior decision or external piece of software (which it sounds like it has not, since you are trying to figure out how to change the format by eliminating the padding you feel is spurious) you should strongly consider dropping binary formats entirely, and moving to a simple text format. I'd describe good ways to do so, but I recently discovered that everything I'd say about data files has already been published, in Jon Bently's book Programming Pearls (or perhaps the sequel, More Programming Pearls). If you must compute the size of a structure less any trailing padding, one way to do so would be struct x x; offsetof(struct x, last_member) + sizeof(x.last_member) offsetof is a (relatively) new macro, standardized by ANSI, and #defined in . (By the way, it is generally agreed that the advantages of having sizeof account for trailing padding far outweigh any disadvantages. Yet this issue apparently belongs in the FAQ as well.) Steve Summit scs@adam.mit.edu