Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize typedef struct

Tags:

c

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;
} PERSON p1 = {"Donald", 4};

Is there a way that I can make a typedef struct and initialize Donald when I define this struct?

like image 268
yemerra Avatar asked Mar 12 '16 11:03

yemerra


People also ask

Can I initialize a 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.

How do you initialize a struct in C?

Structure members can be initialized using curly braces '{}'.

What does typedef struct mean in C?

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 −


1 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};
like image 187
ForceBru Avatar answered Nov 09 '22 10:11

ForceBru