Initialize Typedef Struct
Why Does This Work: Struct Person { Char Name[50]; Short Mental_Age; } P1 = {"Donald", 4}; but Not This: Typedef Struct { Char Name[50]; Short Mental_Age; }...
Why does this 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 make a typedef struct and initialize Donald when I define this struct?
2 Answers
typedefs are aliases for other types. What you're doing is creating a convenience typedef. Since the purpose of a typedef is to create type aliases, you can't define a variable using it.
You have to do this:
typedef struct {
// data
} mytype;
mytype mydata = {"Donald", 4};
The best way, that I know of, is to separate the strict definition from the typedef statement from the struct declaration, similar to:
struct sPerson
{
char name[50];
short mental_age;
};
typedef struct sPerson PERSON;
PERSON p1 = {"Donald", 4};