Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct Initialization Error

I know how to initialize structs (generally), but I'm having troubles with this struct within a struct stuff

typedef struct Location{
    uint8_t x;
    uint8_t y;
} loc;

typedef struct Person{
    loc location;
} person;

global variables:

static person hero;

initialization functions:

void InitializeHero() {
    person hero = {0,0, {0,0}}; // this compiles
    hero.location = {0,0}; // but this does not compile
    hero = {0,0,{0,0}}; // this also does not compile
}
like image 359
Justin Avatar asked Apr 24 '15 23:04

Justin


2 Answers

Your 'this compiles' line is correct; that's an initialization. The other two lines don't compile, because they're not initializations, they're assignments. If you're using a new enough version of C, you could use a compound literal to do the assignments:

hero.location = (loc){0,0};
hero = (person){0,0,{0,0}};

Note - your person hero declaration in InitializeHero shadows the global variable; you probably don't want that.

BTW, are you missing some fields in your person? None of that should compile with what you've shown.

like image 166
Carl Norum Avatar answered Oct 03 '22 17:10

Carl Norum


The line you indicate that compiles produces a warning. Let's break apart your InitializeHero function.

person hero = {0,0, {0,0}};

Here you are instantiating your new person struct named hero. You use the brace initialization method to set the members of the struct. In this case, the only member of person is a loc. A loc itself only has two uint8_ts. Using the brace initialization method here, you would simply use {0, 0}.

Combining these two, you could write a statement like:

person hero = {{0, 0}};

Note that you can only use brace initialization when initializing. Your other two statements are assignments. The struct has already been initialized at this point, which is why those two statements don't compile.

One other note, your global variable static person hero has been shadowed by the local variable hero in InitializeHero. This means that you are creating a separate person struct in your InitializeHero. However, this static variable is initialized where it is declared in this case, so your statement must read

static person hero = {{0, 0}};

...leaving InitializeHero unused.

like image 39
greg Avatar answered Oct 03 '22 18:10

greg