如何知道使用了 Union 中的哪个变量? [英] How to know that which variable from Union is Used?

查看:24
本文介绍了如何知道使用了 Union 中的哪个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将联合声明为:

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

现在,我怎么知道是使用了 Total[7] 还是使用了 TestStruct?

Now, How can I know that whether Total[7] is used or TestStruct is used?

我正在使用 C!我正在重新审视工会和结构,这个问题出现在我的脑海中."sizeof" 不能使用,因为两者的大小相同,即 7 个​​字节.(还有一个问题)

I am using C! I was revisiting unions and structures and this question came to my mind. "sizeof" can't be used as both are of same size i.e. 7 bytes. (And Here comes another question)

当我只用字符 'a' 填充Total"并尝试 sizeof(TestUnionInstance) 时,它返回 12(Char 的大小是 1 个字节,对吧?).所以我把结构从中分离出来,发现结构的大小是 12 个字节而不是 5+2=7 个字节......奇怪!!谁能解释一下??

When I filled only "Total" with a Character 'a' and Tried sizeof(TestUnionInstance), it returned 12 (Size of Char is 1 byte, Right?). So I isolated the structure from it and found that Size of Structure is 12 bytes not 5+2=7 bytes.... Strange!! Anybody can explain??

附言我使用的是 Visual Studio 2008.

P.S. I am using Visual Studio 2008.

推荐答案

你不能.这是工会的一部分.

You can't. That's part of the point of unions.

如果你需要知道,你可以使用一种叫做标记联合的东西.有些语言内置了对这些的支持,但在 C 中,你必须自己做.这个想法是在联合中包含一个标签,您可以使用它来判断它是哪个版本.喜欢:

If you need to be able to tell, you can use something called a tagged union. Some languages have built-in support for these, but in C, you have to do it yourself. The idea is to include a tag along with the union which you can use to tell which version it is. Like:

enum TestUnionTag {NUM_NAME, TOTAL};

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

然后在您的代码中,确保始终设置标签以说明联合的使用方式.

Then in your code, you make sure you always set the tag to say how the union is being used.

关于 sizeof:结构体是 12 个字节,因为 int 有 4 个字节(大多数现代编译器有一个 4 字节的 int,与 long int 相同),然后是三个字节的填充和五个字节的字符(我不知道填充是在字符之前还是之后).填充在那里,因此结构体的长度是整数个字,因此内存中的所有内容都在字边界上保持对齐.因为结构体有 12 个字节长,联合体必须有 12 个字节长才能容纳它;联合不会根据其中的内容改变大小.

About the sizeof: the struct is 12 bytes because there are 4 bytes for the int (most modern compilers have a 4-byte int, the same as a long int), then three bytes of padding and five bytes for the chars (i don't know if the padding comes before or after the chars). The padding is there so that the struct is a whole number of words long, so that everything in memory stays aligned on word boundaries. Because the struct is 12 bytes long, the union has to be 12 bytes long to hold it; the union doesn't change size according to what's in it.

这篇关于如何知道使用了 Union 中的哪个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆