C - change all values ​​of an array of structures in one line

I can declare a structure:

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

Then create an array of structure structures with default values:

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

But after I created the array, is there a way to change the values ​​in the same way as I did above, using only one row, explicitly defining each value without a loop?

+3
source share
4 answers

In C99, you can assign each structure in one line. I do not think that you can assign an array of structures in one line.

C99 introduces complex literals. See Dr. Dobbs's Article here: New C: Compound Literals

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

You can assign to a pointer as follows:

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

memcpy:

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

gcc -std = c99 ( 4.2.4) linux.

, , .

+8

( -1), memset:

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

, , . " "

0

, memcpy, .

, .

0

All Articles