将值赋给c中的全局变量会导致错误

时间:2015-04-12 00:05:37

标签: c struct global-variables

我有以下代码:

struct TreeNode {
     int val;
     struct TreeNode *left;
     struct TreeNode *right;
};


 #define MAXSIZE 1024

 typedef struct stack{
     struct TreeNode volum[MAXSIZE];
     int top;
 }STACK;

 STACK st;
 st.top = -1;

/* other function definitions such as pop() and push() */

但是当我编译它时,它会给我错误Line 18: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token。第18行是st.top=-1;

所以这里我需要初始化堆栈,即将top设置为-1。我也尝试在结构中进行:int top=-1;但是得到了同样的错误。我想知道这样做的正确方法是什么。提前谢谢。

2 个答案:

答案 0 :(得分:1)

你可以尝试

typedef struct stack {
    int top;
    struct TreeNode volum[MAXSIZE];
} STACK;

STACK st = { -1 }; // top has to be the first member of the struct

答案 1 :(得分:1)

st.top = -1;放入某个功能(例如main),因为您无法全局分配。