C - Change all values of an array of structures in one line

让人想犯罪 __ 提交于 2019-12-05 18:51:57

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 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} };

You could use memcpy as well:

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

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.

In case you want to set the values to zero (or -1), you can use memset:

memset(struct_array, 0, sizeof(struct_array));
memset(struct_array, -1, sizeof(struct_array));

i think no, you can only init arrays by this way. but you can change values of structures using 'one-line' method

If the variables are being copied from another source, you can use a method like memcpy to directly overwrite the struct values.

However, the language doesn't provide a direct way to just set the values, other than setting individual elements.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!