Re: About union

From: Kenneth Brody (kenbrody_at_spamcop.net)
Date: 10/02/04


Date: Sat, 02 Oct 2004 10:51:28 -0400

EricLi wrote:
>
> *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.

-- 
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody        | www.hvcomputer.com |                             |
| kenbrody/at\spamcop.net | www.fptech.com     | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+


Relevant Pages