Arrays of Unions

S

Seebs

instead of abcd. Arrays of unions are not sensible even when the types
are consistent!

Of course they are. However, an array of unions, each of which holds a char,
is not the same thing as an array of chars.

You seem to be thinking a union is an object of variable type. It's not.
It's an object of fixed type, which happens to be a container, which contains
one of several possible objects.

-s
 
B

bart.c

main()
{
union { char a; long int b; } u[10];
memset(u, 'x', 10 * sizeof *u);
u[0].a = 'a';
u[1].a = 'b';
u[2].a = 'c';
u[3].a = 'd';
print_chars(u);
putchar('\n');
}

With gcc I get:
./prog
axxx

instead of abcd. Arrays of unions are not sensible even when the types
are consistent!

C doesn't work like that; the 4 char elements are not consecutive (they have
a pitch of sizeof u[0] instead of 1 char).

If the union array elements all happen to contain chars, and you want to
treat the whole thing as a char array or a string, then you need to convert
the array to a string first.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,212
Latest member
BrennaCaba

Latest Threads

Top