1

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.

2
  • 2
    Please don't typedef primitive types with abstract names like you are trying to do. It just causes headaches down the road. Commented Oct 25, 2010 at 0:21
  • @Tim Cooper: I agree, unfortunately it is beyond my control for this project. Commented Oct 25, 2010 at 1:52

4 Answers 4

5

C99 allows it via compound literals:

Bar* f()
{
   Bar* bar = malloc(sizeof(Bar));

   if (bar)
       *bar = (Bar){{1.0, 1.0, 1.0}};

   return bar;
}

The “outer” curlies encapsulate the struct as a whole (if the struct had other members, you'd list them in the outer curlies), and the “inner” curlies are for the array.

Sign up to request clarification or add additional context in comments.

2 Comments

Does this mean you can also do bar->foo = (float[3]){1.0, 1.0, 1.0};?
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.
1

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.

2 Comments

= is well defined for structs. Even structs which contain arrays are assignable.
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.
0

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

1 Comment

Unless it is a member of a struct :)
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.