簡體   English   中英

Struct初始化程序中的匿名聯合

[英]Anonymous Union in Struct Initializer

為什么以下示例在C中不起作用?

#include <stdio.h>

typedef struct {
  int x;
} X;

typedef struct {
  char y[10];
} Y;

typedef struct {
  int pos;
  union {
    X x;
    Y y;
  };
} Test;

int main() {
  X x = { 65 };
  Y y = { "Hallo" };
  Test t = { 1, x }; // OK
  printf("1: %d %d '%s'\n", t.pos, t.x.x, t.y.y);
  Test t2 = { 2, y }; // ERROR
  printf("2: %d %d '%s'\n", t2.pos, t2.x.x, t2.y.y);
  Test t3 = { 3 }; // OK
  printf("3: %d %d '%s'\n", t3.pos, t3.x.x, t3.y.y);
  return 0;
}

main.c:在函數'main'中:
main.c:25:3:錯誤:使用類型'Y'初始化類型'int'時不兼容的類型
測試t2 = {2,y}; //錯誤
^

編輯:順便說一下: t2.y = y; 作品

因為初始化程序的類型不會與union的可能成員進行分析和匹配。

相反,您只是應該為第一個union成員提供初始化程序。

C11草案§6.7.9.17:

每個大括號括起的初始化列表都有一個關聯的當前對象。 當沒有指定時,根據當前對象的類型按順序初始化當前對象的子對象:增加下標順序的數組元素,聲明順序中的結構成員,以及union的第一個命名成員。

如上所述,您可以使用指示符來控制:

Test t2 = { 2, .y = y };

應該工作( .y是指定者,C99中的“新”)。

您必須指定您正在初始化第一個以外的成員:

 Test t2 = { 2, { .y = y } } ;

否則編譯器將嘗試初始化它,就像你寫了: .x = y

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM