【问题标题】:anonymous union inside structure结构内部的匿名联合
【发布时间】:2017-05-25 05:14:01
【问题描述】:

以下代码提供了一个 O/P : 101:name_provided:name_provided

AFAIK 工会一次只能容纳一个成员,但看起来这两个值都是可见的,这是正确的还是代码有什么问题。

#include <stdio.h>

struct test1{
    char name[15];
};

struct test2{
    char name[15];  
};

struct data{
    int num;
    union{
        struct test1 test1_struct;
        struct test2 test2_struct;
    };
};

int main()
{
    struct data data_struct={101,"name_provided"};
    printf("\n%d:%s:%s",data_struct.num,data_struct.test1_struct.name,data_struct.test2_struct.name);
    return 0;
}

【问题讨论】:

  • C 不会阻止您访问与您分配的工会成员不同的工会成员,这只是未指定的行为。虽然当两个结构相同时,我认为它总是可以的。
  • 你希望发生什么?
  • @n.m. ,匿名联合中只有一个结构(test1_struct或test2_struct)可以保存值,另一个将打印垃圾
  • 有时垃圾看起来合法只是因为它随机落在恰好存储合法值的内存区域中。但是,在您的情况下,输出定义明确而不是垃圾,因为两个联合成员是“相似”结构,并且语言标准专门定义了这种情况。所以它保证打印它打印的内容(而不是“发生打印”)。
  • 还有一个小的代码更新,struct test1{ char name[10]; }; struct test2{ char name[15]; }; O/P 更改为:101:name_provi:name_provi 是不是就像下面的代码一样,struct data data_struct={101,"name_provided"}; test1_struct 的名称将获得值,并且test2_struct 的名称将打印垃圾,而不是为具有更大存储空间的成员分配内存。

标签: c struct unions anonymous


【解决方案1】:

联合指定两个成员将位于内存中的同一位置。因此,如果您分配给test1_struct,然后从test2_struct 读取,它会将test1_struct 的内容解释为test2_struct 的格式。

在这种情况下,两个结构具有相同的格式,因此您读取和写入哪个结构没有区别。使用两个成员相等的联合通常是没有意义的。联合的通常目的是拥有不同类型的成员,但不需要为每个成员单独分配内存,因为您一次只需要使用一种类型。有关典型用例,请参阅 How can a mixed data type (int, float, char, etc) be stored in an array?

请参阅Unions and type-punning,了解访问与您分配的成员不同的成员的后果。

【讨论】:

    猜你喜欢
    • 2019-06-01
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 2011-07-01
    相关资源
    最近更新 更多