C - 在一行中更改结构数组的所有值

Jef*_*amb 3 c arrays structure initialization

我可以声明一个结构:

typedef struct
{
  int var1;
  int var2;
  int var3;
} test_t;
Run Code Online (Sandbox Code Playgroud)

然后使用默认值创建这些结构结构的数组:

test_t theTest[2] =
{
   {1,2,3},
   {4,5,6}
};
Run Code Online (Sandbox Code Playgroud)

但是在我创建数组之后,有没有办法像上面一样改变值,只使用一行,明确指定每个值而没有循环?

Kar*_*and 8

在C99中,您可以在一行中分配每个结构.我不认为你可以在一行中分配结构数组.

C99引入了复合文字.请参阅Dr. Dobbs这里的文章: 新C:复合文字

theTest[0] = (test_t){7,8,9};
theTest[1] = (test_t){10,11,12};
Run Code Online (Sandbox Code Playgroud)

你可以分配给这样的指针:

test_t* p; 
p = (test_t [2]){ {7,8,9}, {10,11,12} };
Run Code Online (Sandbox Code Playgroud)

你也可以使用memcpy:

memcpy(theTest, (test_t [2]){ {7,8,9}, {10,11,12} }, sizeof(test_t [2]);
Run Code Online (Sandbox Code Playgroud)

以上在linux上使用gcc -std = c99(版本4.2.4)进行了测试.

您应该阅读Dr. Dobbs的文章,了解复合文字的工作原理.