How to know that which variable from Union is Used?

后端 未结 6 976
北荒
北荒 2021-02-01 22:32

If I declare a Union as:

union TestUnion
{
    struct 
    {
      unsigned int Num;
      unsigned char Name[5];
    }TestStruct;
    unsigned char Total[7];
};         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-01 23:03

    First, sizeof(int) on most architectures nowadays is going to be 4. If you want 2 you should look at short, or int16_t in the stdint.h header in C99 if you want to be specific.

    Second, C uses padding bytes to make sure each struct is aligned to a word-boundary (4). So your struct looks like this:

    +---+---+---+---+---+---+---+---+---+---+---+---+
    |      Num      |   N   a   m   e   |   |   |   |
    +---+---+---+---+---+---+---+---+---+---+---+---+
    

    There's 3 bytes at the end. Otherwise, the next struct in an array would have it's Num field in an awkwardly-aligned place, which would make it less efficient to access.

    Third, the sizeof a union is going to be the sizeof it's largest member. Even if all that space isn't used, sizeof is going to return the largest result.

    You need, as other answers have mentioned, some other way (like an enum) to determine which field of your union is used.

提交回复
热议问题