Design Initialization Error

I know how to initialize structures (usually), but I am having problems with this struct inside the structural material

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 } 
+6
source share
2 answers

Your line "this compiles" is correct; what initialization. The remaining two lines are not compiled, because they are not initializations, they are assignments. If you are using a fairly new version of C, you can use a compound literal to complete the tasks:

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

Note. Your person hero declaration in InitializeHero obscures the global variable; you probably don't want this.

By the way, are you missing some fields in person ? None of this should compile with what you showed.

+3
source

On the line, you indicate that the compiler generates a warning. Let me break your InitializeHero function.

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

Here you create a new person structure named hero . You use the parenthesis initialization method to set structure members. In this case, the only member of person is loc . A loc has only two uint8_t s. Using the parenthesis initialization method here, you simply use {0, 0} .

By combining these two, you can write an instruction like:

person hero = {{0, 0}};

Note that you can use parenthesis initialization during initialization. Your other two statements are appointments. The structure has already been initialized at this point, so these two statements are not compiled.

One more note: your global variable static person hero been obscured by the local hero variable in InitializeHero . This means that you are creating a separate person structure in your InitializeHero . However, this static variable is initialized where it is declared in this case, so your operator should read

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

... leave InitializeHero not used.

+1
source

Source: https://habr.com/ru/post/985918/


All Articles