Ç - 更改一行结构数组的所有值 [英] C - Change all values of an array of structures in one line

查看:121
本文介绍了Ç - 更改一行结构数组的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以声明结构:结果

typedef struct
{
  int var1;
  int var2;
  int var3;
} test_t;

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

Then create an array of those structs structure with default values:

test_t theTest[2] =
{
   {1,2,3},
   {4,5,6}
};

不过,我已经创建数组后,有没有什么办法改变以同样的方式我上面那样,只用一条线的数值,显式指定每个值没有一个循环?

But after I've created the array, is there any way to change the values in the same way I did above, using only one line, specifying every value explicitly without a loop?

推荐答案

在C99可以在一行分配每个结构。我不认为你可以结构的排列在同一行,虽然分配。

In C99 you can assign each structure in a single line. I don't think that you can assign the array of structs in one line though.

C99引入了复合文字。见多布斯医生文章在这里:新C:复合文字

C99 introduces compound literals. See the Dr. Dobbs article here: The New C: Compound Literals

theTest[0] = (test_t){7,8,9};
theTest[1] = (test_t){10,11,12};

您可以分配到这样一个指针:

You could assign to a pointer like this:

test_t* p; 
p = (test_t [2]){ {7,8,9}, {10,11,12} };

您可以使用memcpy的还有:

You could use memcpy as well:

memcpy(theTest, (test_t [2]){ {7,8,9}, {10,11,12} }, sizeof(test_t [2]);

上面带有测试的的gcc -std = C99 (版本4.2.4)在Linux上。

Above tested with gcc -std=c99 (version 4.2.4) on linux.

您应该阅读多布斯博士的文章,了解如何文字工作的复合

You should read the Dr. Dobbs article to understand how compound literals work.

这篇关于Ç - 更改一行结构数组的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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