简体   繁体   中英

struct initialization in C

Before you mark it as a duplicate/downvote, I have read books, spend decent amount of time on Internet researching this, but I CANNOT find an answer.

I want to initialize my struct when I create it. But I also want to declare it as a type using typedef

Here is what I am trying to do

typedef struct Clock_TAG Clock;

struct Clock_TAG{
  int time;
}Clock = {
  0
};

And it gives me an error "redefinition of 'Clock' as different kind of symbol"

typedef struct Clock_TAG{
 int time;
}Clock = {
  0
};

Gives "illegal initializer (only variables can be initialized)"

I know I have to use the name of the struct in order to initialize it, I want to initialize it at the time of it's creation, so please do not suggest having an init() method.

This is an example code, I want to specifically understand HOW I can have a typedef AND struct initialization in the .h file I know there are many ways around this, I can omit using typedef or initialize the struct members the other way, but I want to understand why this gives me an error and how to fix it.

PS Is it also legal to malloc the struct in .h file?

A typedef is an alias, when stating:

typedef struct Clock_TAG Clock;

and stating after that typedef:

struct Clock_TAG{
  int time;
} Clock = {0};
  ^^^^^

You're trying to initialize a struct name. Probably what you meant was:

typedef struct Clock_TAG Clock;

struct Clock_TAG{
  int time;
} clock = {0}; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM