views:

894

answers:

4

I can declare a structure:

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?

A: 

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

f0b0s
Did you mean 'cannot change values'? See also the answer mentioning C99.
Jonathan Leffler
sorry, i use only -c99 and didn`t mention that. i often use this feature: "theTest[0] = (test_t){7,8,9};"
f0b0s
A: 

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.

Reed Copsey
You've forgotten about C99.
Jonathan Leffler
+1  A: 

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));
Mehrdad Afshari
True, but not very complete. You have forgotten about C99.
Jonathan Leffler
I just mentioned this as an alternative method for a common particular case of the problem. I didn't claim it solves the complete problem.
Mehrdad Afshari
+7  A: 

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.

Karl Voigtland
I'll try out a combination of these to see if it works.
Jeff Lamb
With that, you could create a macro for a assignment loop. That way, it's easy to reuse and very clean.
Loki
+1 for knowing that C99 can do it, even though C89 cannot.
Jonathan Leffler