A Question about nesting structures

John Crane crane at fortune.UUCP
Wed Apr 11 07:04:59 AEST 1984


I am trying to read a file with a lot of repetitive data structures
such as dates and times. I need to access days, months, years, hours,
and seconds, so I thought nesting a structure within a structure
would do the trick. However, I find that (at least in Fortune's C
compiler) structures are always started on an even byte boundary. This
causes the compiler to skip bytes and throw off the rest of the record.

Here is an example of what I mean:

struct time
{
	char hh[2];
	char mm[2];
	char ss[2];
}

struct date
{
	char mm[2];
	char dd[2];
	char yy[2];
}

struct input
{
	char name[25];
	struct date birth;
	...
} cust

The problem is when I access  cust.birth.mm, I want bytes 25 and 26. What
I get is bytes 26 and 27 because struct date birth is even-aligned.

Why do structures have to be even-aligned? Is there any other way to
do what I want to do besides spelling out every field in detail?

It seems to me that structures lose some of their value if you can't
nest them with confidence.

The world doesn't always end on even boundaries. Especially if you
are reading somebody else's data.

John Crane



More information about the Comp.lang.c mailing list