sizeof struct

Steve Summit scs at hstbme.mit.edu
Thu Sep 7 13:01:24 AEST 1989


In article <2951 at cbnewsc.ATT.COM> hartman at cbnewsc.att.com (mark.a.hartman) writes:
>The AT&T 3B20 compiler rounds structures up to an even word length,
>in your case from 42 bytes to 44.  If you need code that is portable
>between the two machines, try adding something like
>	char	fill[2];
>to the end of the structure to fill it out.  Then, "sizeof struct"
>will be the same on both machines.

If you need code that is portable between machines, don't rig it
up so that you depend on things like structure sizes.  One way to
depend on structure size (and arrangement, and byte order, etc.)
is to pass data between the machines (over the network, or on
magnetic media) by writing and reading whole structures.  A much
better approach is to write and read an ASCII, machine-
independent format.

If you must pad a structure out to some known size, a common
technique is to stick it in a union along with a buffer of the
desired size:

	union tblock {		/* from memory; can't find tar.c or tar.h */
		struct header {
			char name[100];
			char uid[8];
			char linktype;
		} header;
		char dummy[512];
	};

As long as sizeof(struct header) is less than 512,
sizeof(union tblock) will be exactly 512.  (This used to be the
case; one of the ANSI C experts will now point out that some
clause in the standard allows a compiler writer to implement
things such that sizeof(struct header) could be almost anything.)

                                      Steve Summit



More information about the Comp.lang.c mailing list