This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: float, int length varies inside struct ???


tommya90@my-deja.com wrote:


: Hi,

: I have a structure with a mixture of
: shorts, int and floats. What really bugs
: me is that floats and ints sometimes
: are 6 byte and sometimes 4 byte, which
: they are supposed to be.

	They aren't "longer", but there is "padding"
between them to make sure that 4-byte quantities
start on 4-byte boundaries, etc. On some CPUs
(x86, if the "trap unaligned access" bit is off),
unaligned accesses are merely slower. On others,
they will either cause an exception (e.g. 68000),
or quietly produce garbage results (e.g. PC/RT).
Contrary to the remarks already made by another
poster, it is pretty much _never_ a good idea to
squirt a raw struct over a network connection, or
even store one in a file. That post did correctly
identify one problem: if the API you are using
was compiled with one sort of alignment, and you
compile with another, you are in for a world of
hurt.

: I've had
: this problem before, and then I just
: divided the structures into structs
: with float and structs with shorts.

	Well, that's one way. Another is to
"hand pack" the struct, starting it off with
the largest data-type (e.g. double), followed
by the next-largest (typically floats and ints,
or longs on some platforms), then shorts, etc.
Since you aren't saving these into files or
squirting them over the net, you can easily
re-order the elemnts of a struct without changing
any code, which just uses the names. You could
also insert "dummy" short or whatever to even
thing out, but that's often more tedious.

	Of course, this doesn't help if your
structure really _is_ something like

struct inner {
	float fval;
	short sval;
};

struct outer {
	struct inner bundle[23]
};

Because struct inner is going to be padded to 8 bytes
by a compiler that cares about performance. Life
is tough. If it was easy, they'd get someone cheaper
than you to do it... :-)

					Mike
| albaugh@agames.com, speaking only for myself


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]