1

我想初始化 mainstr 的所有三个数组,有人可以帮我在结构中初始化这个匿名联合吗?第 0 个索引应该用整数数组初始化,第 1 个和第 2 个索引应该用 char 指针初始化。

typedef struct
{
   int testy;
   union
   {
      int a[3];
      char* b[3];
   }
   bool testz;
} testStr;


typedef struct
{
    testStr x[3];
} mainStr;

像这样的东西,

mainStr test = {
                  {20, {{10, 20, 30}}, FALSE},
                  {10, {{"test1", "test2", NULL}}, TRUE},
                  {30, {{"test3", "test4", NULL}}, FALSE},
              }
4

3 回答 3

0

使用指示符

mainStr test = {{
                {20, {{10, 20, 30}}, false},
                {10, {.b={"test1", "test2", NULL}}, true},
                {30, {.b={"test3", "test4", NULL}}, false},
               }};

演示

于 2021-07-05T10:46:36.897 回答
0

有点工作,但可行。

#include <stdbool.h>
int foo() {
  typedef struct {
    int testy;
    union {
      int a[3];
      char *b[3];
    };
    bool testz;
  } testStr;

  typedef struct {
    testStr x[3];
  } mainStr;

  testStr test1 = {20, { {10, 20, 30}}, false};
  (void) test1;

  mainStr test = { //
      { //
          {20, { {10, 20, 30}}, false}, //
          {10, { .b={"test1", "test2", NULL}}, true}, //
          {30, { .b={"test3", "test4", NULL}}, false} //
          }//
      };
  (void) test;
}
于 2021-07-05T10:46:50.963 回答
0

一些问题:

  • union { ... };必须以分号结尾。
  • 使用标准bool而不是某些自制版本。
  • mainStr意味着需要一对额外的初始化器,一个用于结构,一个用于数组成员x

修复了这些问题后,您可以使用指定的初始化程序来告诉编译器您正在初始化哪个联合成员:

#include <stdbool.h>

typedef struct {
  int testy;
  union {
    int a[3];
    char* b[3];
  };
  bool testz;
} testStr;

typedef struct {
  testStr x[3];
} mainStr;

int main (void) {
  mainStr test = 
  {
    {
      {20, .a = {10, 20, 30}, false},
      {10, .b = {"test1", "test2", 0}, true},
      {30, .b = {"test3", "test4", 0}, false},
    }
  };
}

不过,为所有结构/联合成员使用指定的初始化程序可能是一个好主意,以获得自记录代码。

于 2021-07-05T10:58:20.153 回答