[英]structure member accessing error
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
typedef struct {
int tos;
char stackarr[];
}STACK;
STACK paren;
paren.tos = -1;
void push()
{
paren.tos++;
paren.stackarr[tos] = '(';
}
This is giving me the following error: 这给了我以下错误:
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
paren.tos = -1;
^
In function ‘push’:
error: ‘tos’ undeclared (first use in this function)
I'm a beginner and have no idea why I'm getting this error. 我是初学者,不知道为什么我会收到这个错误。 Any ideas? 有任何想法吗?
You cannot perform an assignment outside a function; 您不能在函数外执行赋值; only initialization is allowed ( demo ): 只允许初始化 ( 演示 ):
STACK paren = {.tos = -1};
With this part out of the way, your approach is not going to work: flexible members, ie char stackarr[]
at the end of the struct
, do not work in statically allocated space; 有了这个部分,你的方法就不会起作用了:灵活的成员,即struct
末尾的char stackarr[]
,不能在静态分配的空间中工作; you need to use dynamic allocation with them. 你需要使用动态分配。 See this Q&A for an illustration of how to use flexible struct members. 有关如何使用灵活结构成员的说明,请参阅此问答 。
Alternatively, you can pre-allocate the max number of elements to stackarr
, ie 或者,您可以将最大数量的元素预分配给stackarr
,即
typedef struct {
int tos;
char stackarr[MAX_STACK];
} STACK;
STACK paren = {.tos = -1};
The obvious limitation to this approach is that the stack cannot grow past its preallocation limit. 这种方法的明显局限性是堆栈不能超过其预分配限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.