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?
When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.
Structure members can be initialized using curly braces '{}'.
You can use typedef to give a name to your user defined data types as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows −
typedef
s 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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With