Initialize typedef structure

Why does it work:

struct person { char name[50]; short mental_age; } p1 = {"Donald", 4}; 

But not this:

 typedef struct { char name[50]; short mental_age; } PERSON p1 = {"Donald", 4}; 

Is there a way that I can create a typedef structure and initialize Donald when I define this structure?

+7
c struct
source share
2 answers

typedef are aliases for other types. What you do creates the convenience of typedef . Since the purpose of typedef is to create type aliases, you cannot define a variable using it.

You must do this:

 typedef struct { // data } mytype; mytype mydata = {"Donald", 4}; 
+5
source share

The best way I know is to separate a strict definition from a typedef statement from a structure declaration, similar to:

 struct sPerson { char name[50]; short mental_age; }; typedef struct sPerson PERSON; PERSON p1 = {"Donald", 4}; 
+2
source share

All Articles