[net.lang.c] A Question about nesting structures

crane@fortune.UUCP (John Crane) (04/10/84)

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

ntt@dciem.UUCP (Mark Brader) (04/11/84)

Mr. Crane, C is not COBOL, and structs are not "group items".
You know that this will not work:

	struct x { char a; int b; } y;
	read (0, &y, 3);

What you are supposed to do is read each item individually.
I don't think that it should make any difference that the items within
the group all turn out to be chars in the end.

I think you should use scanf instead of trying to read everything at once.

Mark Brader