C 会员申请';s';在非结构或联盟中
我尝试使用结构数组,每次我尝试为任何结构赋值时,都会出现以下错误:C 会员申请';s';在非结构或联盟中,c,C,我尝试使用结构数组,每次我尝试为任何结构赋值时,都会出现以下错误: request for member 's' in something not a structure or union 我的结构: struct { char s; int lineNum; } item; 我这样宣布: struct item * stack[100]; 然后: /* both lines gives me the error */ stack[0].s = 'a'; s
request for member 's' in something not a structure or union
我的结构:
struct {
char s;
int lineNum;
} item;
我这样宣布:
struct item * stack[100];
然后:
/* both lines gives me the error */
stack[0].s = 'a';
stack[0].lineNum = 1;
我在这里遗漏了什么吗?您没有结构项
stack
是一个100指针数组,指向一个尚未定义的结构
试一试
堆栈
不是项
的数组,它是指向项
的指针数组,因此您需要在尝试使用它们之前取消对它们的引用:
(*(stack[0])).s = 'a';
(*(stack[0])).lineNum = 1;
struct item stack[100]
是您想要的后续代码。您拥有的是一个指针数组,如果您希望使用每个指针,则需要在声明之前进行分配 您尚未定义结构项
。您当前有一个名为项的匿名结构的变量。您似乎忘记包含typedef
:
typedef struct { ... } a_t; // can use "a_t" as type.
struct a { ... }; // can use "struct a" as type.
typedef struct a { ... } a_t; // can use "struct a" or "a_t" as type.
你需要这个:
struct item {
char s;
int lineNum;
} ;
...
struct item * stack[100];
...
stack[0]->s = 'a';
stack[0]->lineNum = 1;
但要注意:您需要为堆栈中的每个项分配内存<代码>堆栈
包含100个指向结构项
s的指针,但每个指针都包含垃圾(它们都指向无效内存)
对于stack
中的每个元素,您需要像这样分配内存stack[n]=malloc(sizeof struct item)
尝试过,现在错误更改为:取消对不完整类型的指针的引用仅供参考:您的结构构造定义了一个名为item
的对象。它的类型是一个两字段结构,没有标记或别名(typedef
),加上@pmg的答案
struct item {
char s;
int lineNum;
} ;
...
struct item * stack[100];
...
stack[0]->s = 'a';
stack[0]->lineNum = 1;