struct initialization in C

时间:2015-10-30 23:12:43

标签: c struct initialization

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.

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

1 个答案:

答案 0 :(得分:3)

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