1

I am learning about nested structs in C, and what I want to do is to be able to assign a value to my struct's member struct. I'm having trouble figuring this out, and I don't want to force myself to initialize the member struct in the initialization of the struct. Why do I keep getting an error when I try to compile this code?

main.c: In function 'main': main.c:16:23: error: expected expression before '{' token fooPerson.fullname = {"Foo", 'B', "Baz"}; 

 

#define LEN 20 struct names { char first[LEN]; char middle; char last[LEN]; }; struct person { struct names fullname; }; int main() { struct person fooPerson; fooPerson.fullname = {"Foo", 'B', "Baz"}; // NOT this: it works, but not the solution I'm asking for // struct person fooPerson = {{"Foo", 'B', "Baz"}}; } 
2
  • You can only initialize something once. And arrays are not assignable. Commented Sep 23, 2015 at 6:28
  • Right, I edited the title to reflect your comment. Commented Sep 23, 2015 at 6:38

2 Answers 2

6

Starting in C99, you can use a compound literal for this:

fooPerson.fullname = (struct names){ "Foo", 'B', "Baz" }; 

If you’re stuck with C89, though, you’re mostly out of luck, unless you want to do something like this:

{ struct names n = { "Foo", 'B', "Baz" }; fooPerson.fullname = n; } 

Felix points out in the comments that neither of these are truly initialization—it’s only initialization when it happens as part of the declaration, which isn’t the case here. Rather, both are assignments. Still, this ought to do what you want.

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

4 Comments

dropping my answer for this, but please add it's not initialization, because initialization happens (by definition) in the declaration.
Yes please point out that none of this is initialization, as the OP is confused about the term. Also in C89, nothing is stopping you from declaring a second struct variable, initialize it and copy it in runtime. Which is what this code is doing. fooPerson = n; would work perfectly fine in C89, no need for memcpy as there are no pointers here.
@Lundin: I’m not sure what I was thinking with the memcpy. In any case, I edited it to be a normal assignment.
@icktoofay I mainly wanted to point out that there's no notable difference between C99 and C90 for this example. Either allow you to create a temporary object and do runtime assignment.
1

Initialization is the term for giving a variable a value upon declaration. Everything else is assignment.

Thus if you initialize your variable, and only then, you can use an initializer list (the { }).

struct person fooPerson = { {"Foo", 'B', "Baz"} }; 

Alternatively you can use designated initializers:

struct person fooPerson = { .fullname = { .first = "Foo", .middle = 'B', .last = "Baz" } }; 

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.