[英]Can't assign struct variable in header file
I have a header file including a structure like this: 我有一个头文件,包括这样的结构:
typedef struct
{
int index = -1;
stack_node *head;
} stack;
But when compiling with cc it shows error at the assignment line ( int index = -1
): 但是当用cc编译时,它在赋值行显示错误(
int index = -1
):
error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
should I add an initialization function to initialize variables? 我应该添加初始化函数来初始化变量吗?
What you provide is not a variable declaration but a type definition. 您提供的不是变量声明,而是类型定义。 You can't assign default values to struct fields in a typedef.
您不能将默认值分配给typedef中的struct字段。
If you want to assign an initial value to a struct variable, you should try: 如果要为结构变量分配初始值,则应尝试:
stack myStack = { .index = 1 };
This works in C99. 这适用于C99。
typedef struct
{
int index;
stack_node *head;
} stack;
stack getStack()
{
stack st;
st.index = -1;
return st;
}
In C, you can't assign variables inside the struct. 在C中,您无法在结构内部分配变量。
You should initialise them in another function when each instance is created, however. 但是,您应该在创建每个实例时在另一个函数中初始化它们。
You can't assign a value in struct declaration like that. 你不能像这样在struct声明中赋值。
stack s = { -1, 0 };
Try this. 尝试这个。
Technically, if you are using C++ you can define constructor for struct. 从技术上讲,如果您使用的是C ++,则可以为struct定义构造函数。 I don't think this work for C. Use the above if you are strictly in a C environment.
我不认为这适用于C.如果您严格在C环境中,请使用上述内容。
typedef struct _stack
{
int index = -1;
stack_node *head;
_stack() {
index = -1;
head = 0;
}
} stack;
Something like this. 像这样的东西。 Let me know if it doesn't work cause I writing base on a few memory and haven't write much C for quite a while.
让我知道它是否不起作用因为我写了一些基于几个内存并且已经写了很多C很长一段时间了。
UPDATE: I like @mouviciel answer, I didn't know you could initialize individual member variable by prefixing . 更新:我喜欢@mouviciel答案,我不知道你可以通过前缀来初始化单个成员变量。 in front.
在前。 Learnt something.
学到了一些东西。 Thanks.
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.