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

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

0

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};
6

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};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest