Unions and structures in C
Steve Willoughby
steve at aardvark.UUCP
Sat Jan 30 19:36:32 AEST 1988
In article <1520 at phoenix.Princeton.EDU> asjoshi at phoenix.Princeton.EDU (Amit S. Joshi) writes:
>Hello,
>
>I have a question about unions and structures in C:
>Suppose I have the following fragment of a program :
>
>struct one { float x,y; };
>union two { float x[2];
> struct one one; };
>main () {
> union two two;
> two.one.x = 1.0; two.one.y = 2.0;
> printf(" x = %f, y = %f\n",two.one.x,two.one.y);
> printf(" x[%d] = %f, x[%d] = %f\n",1,two.x[0],2,two.x[1]);
>}
>My question is what would the second printf statement print ?
For the C compilers I have used, the second printf statement
would be the same as the first, i.e.,
x = 1.0, y = 2.0
x[1] = 1.0, x[2] = 2.0
Supposedly, the members of a union should line up like you expect
here (as long as you don't create any alignment problems, which
I don't think you would with the float's here).
You should create a memory area that looks like this:
.___.___.___.___.___.___.___.___.
| first_float | second_float |
|___.___.___.___|___.___.___.___|
"two.x[0]" "two.x[1]" -- two floats called x
"two.one.x" "two.one.y" -- two floats called x and y
Lattice C does something like this for defining CPU registers
as a union of two identically-sized structures; one structure
defines registers as chars (individual bytes addressable), while
the other defines regs as ints (addressable in two-byte pairs).
You can freely mix the two -- assign values to some members as
ints and others as chars (each time using the appropriate union
member). This works because the union members match up exactly.
There could be some structs that won't behave so nicely (again,
if you've got things in them that need to be padded out to word
boundaries or such).
--
"I am always doing what I cannot do yet, in order to learn how to do it."
-- Vincent van Gogh
Steve Willoughby (UUCP: ...!ihnp4!tektronix!tessi!aardvark!steve)
More information about the Comp.lang.c
mailing list