About union

E

EricLi

*typedef struct ct_data_s {
union {
long freq; /* frequency count */
long code; /* bit string */
} fc;
union {
char dad; /* father node in Huffman tree */
char len; /* length of bit string */
} dl;
} ct_data;

void main( )
{
int i = sizeof( ct_data );
}*


why does i equal 8?
I think the result is 5(sizeof(long)+sizeof(char))


-
EricL
 
K

Kenneth Brody

EricLi said:
*typedef struct ct_data_s {
union {
long freq; /* frequency count */
long code; /* bit string */
} fc;
union {
char dad; /* father node in Huffman tree */
char len; /* length of bit string */
} dl;
} ct_data;

void main( )
{
int i = sizeof( ct_data );
}*

why does i equal 8?
I think the result is 5(sizeof(long)+sizeof(char)).

Because, on your platform, longs must be aligned on a 4-byte boundary.
Therefore, if you were to make an array of ct_data elements, the second
element would have to be aligned at offset 8. Therefore, sizeof(ct_data)
must be 8.
 
M

Martin Ambuhl

EricLi said:
*typedef struct ct_data_s {
union {
long freq; /* frequency count */
long code; /* bit string */
} fc;
union {
char dad; /* father node in Huffman tree */
char len; /* length of bit string */
} dl;
} ct_data;

void main( )
^^^^^^
After this illiteracy, no one can say what your program should do.
{
int i = sizeof( ct_data );
}*


why does i equal 8?

It could have been 42.
I think the result is 5(sizeof(long)+sizeof(char)).

You are wrong. Check the FAQ before posting next time.
 

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

Members online

No members online now.

Forum statistics

Threads
474,147
Messages
2,570,833
Members
47,377
Latest member
MableYocum

Latest Threads

Top