[net.lang.c] alignment of struxures

cottrell@nbs-vms.ARPA (01/04/85)

/*
1) why not make all struxures unaligned, requiring explicit alignment
   by the programmer? pdp-11 (& vax?) assemblers require an explicit
   '.even' or such. i know it's a burden, but then any struxure would
   be possible.
2) in the meantime, try this:

	#define BYTE(x)	(*((char *)(x)))
	#define WORD(x) (*((short*)(x)))
	#define LONG(x) (*((long *)(x)))

then

	struct ugly {
		char	a;
		char	longint[4];	/* really a long int */
		...
	} yuk;

to get the long int do:

	barf = LONG(yuk.longint);

3) have fun!

*/

Bob Larson <BLARSON%ECLD@usc-ecl.ARPA> (01/04/85)

Not at all portable.  Many machines KNOW (and need to know) that all
pointers to long (for example) are always aligned on a long word boundary.
Since the same machines force alignment of structures, structure assignment
won't work either.  The only type of copy that will work is the appropriate
number of char assignments.  (Of course a loop, macro, or function can be
used.) (To bad C doesn't have array assignments.)  (This assumes that
everything is an integral number of bytes... True on most machines.  (I
think pcc for tops-20 uses 36 bit characters... yuck.))

Bob Larson <Blarson@Usc-Ecl.Arpa>
-------

kre@munnari.OZ (Robert Elz) (01/06/85)

In article <6954@brl-tgr.ARPA> cottrell@nbs-vms.ARPA writes:

| 2) in the meantime, try this:
| 
| 	#define LONG(x) (*((long *)(x)))
| then
| 	struct ugly {
| 		char	a;
| 		char	longint[4];	/* really a long int */
| 		...
| 	} yuk;
| 
| to get the long int do:
| 
| 	barf = LONG(yuk.longint);

Quite apart from possibly causing "segmentation violation - core dumped"
on those hosts that like aligned longs, it's also not guaranteed to work.

Compilers are allowed to put padding "anywhere" inside a struct/union,
all they need to do is leave the order alone.  One of the compilers
I work with would put 3 bytes of padding between "a" and "longint"
in the structure above...

Robert Elz					decvax!mulga!kre