tags:

views:

75

answers:

4

I have a struct with an array as a member, and am trying to set that array using arrow syntax. What I have:

typedef float Foo[3];
typedef struct {
  Foo foo;
} Bar;

Bar* f() {
  Bar* bar = malloc(sizeof(Bar));
  bar->foo = {1.0, 1.0, 1.0};

  return bar;
}

gcc says:

error: expected expression before '{' token

on the line bar->foo = {1.0, 1.0, 1.0};

I'm at a loss why this doesn't work. Thanks in advance.

+1  A: 

Because C can't copy arrays through assignment. The only place that you can ever use the {1.0, 1.0, 1.0} syntax is in the initialization of a variable:

float foo[3] = {1.0, 1.0, 1.0};

It's just not something that the language supports. It's possible that this is because that would allow the = operator to take an indefinite and possibly very long amount of time to perform the copy—it's a philosophical question.

John Calsbeek
`=` is well defined for structs. Even structs which contain arrays are assignable.
dreamlax
That's true, assignment works for structs. It's an obscure corner of the language that it works for structs that contain arrays. Something to take up with the designers.
John Calsbeek
A: 

It's not a supported syntax. You can only initialize arrays when they are created -- you can't assign to one that is created.

Lou Franco
Unless it is a member of a struct :)
dreamlax
+5  A: 
dreamlax
Does this mean you can also do `bar->foo = (float[3]){1.0, 1.0, 1.0};`?
Jack Kelly
No, because `=` is not defined for array types, but it is defined for struct types (even for structs that contain arrays). See §6.5.16.1 for more information about assignment.
dreamlax
A: 

Try

float bar[3] = {1.0, 2.0, 3.0};
float foo[3];
foo = {1.0, 2.0, 3.0};

That is an example of the difference between initialization and assignment, and there is no assignment operator for arrays in c.

Note however that you can do

Bar baz, quix
/* quix get setup some how... */
bar = quix;

because there is an assignment operation on structs, which is how dreamlax's answer works.

dmckee