breadjesus
breadjesus

Reputation: 2059

C: setting an array member of a struct through a pointer

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.

Upvotes: 1

Views: 868

Answers (4)

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.

Upvotes: 0

dreamlax
dreamlax

Reputation: 95405

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.

Upvotes: 5

Lou Franco
Lou Franco

Reputation: 89242

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

Upvotes: 0

John Calsbeek
John Calsbeek

Reputation: 36547

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.

Upvotes: 1

Related Questions