Re: sizeof a union




"Mockey Chen" <mockey.chen@xxxxxxxxxx> wrote in message
news:dmhr15$9l8$1@xxxxxxxxxxxxxxxxx
> My friend ask me a question as following:
>
> give a union SU define as:
> typedef union _SU
> {
> short x;
> struct y{
> char a;
> short b;
> char c;
> };
> }SU;
>
> what is the sizeof (SU)?
>
> My compiler tell me the answer is 6.
> I want to know why the answer is 6.


Why not add another member and use that to 'explore' the other members,
e.g.,:

#include <stdio.h>

typedef union
{
int x;

struct
{
int a;
int b;
char c;
} y;

struct
{
unsigned char a;
unsigned char b;
unsigned char c;
unsigned char d;
unsigned char e;
unsigned char f;
} z;
}SU;

int main(void)
{
SU a;

printf("x = \t%p\n", &a.x);

printf("y.a = \t%p\n", &a.y.a);
printf("y.b = \t%p\n", &a.y.b);
printf("y.c = \t%p\n", &a.y.c);

printf("z.a = \t%p\n", &a.z.a);
printf("z.b = \t%p\n", &a.z.b);
printf("z.c = \t%p\n", &a.z.c);
printf("z.d = \t%p\n", &a.z.d);
printf("z.e = \t%p\n", &a.z.e);
printf("z.f = \t%p\n", &a.z.f);

return 0;
}


.



Relevant Pages