要求会员'不是结构或工会

时间:2014-03-21 16:40:06

标签: 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';
    stack[0].lineNum = 1;

我在这里错过了什么吗?

5 个答案:

答案 0 :(得分:8)

您没有struct item

stack是一个100指针,指向尚未定义的结构。

尝试

struct item {
    char s;
    int lineNum;
};

答案 1 :(得分:3)

你需要这个:

struct item {
    char s;
    int lineNum;
} ;
...
struct item * stack[100];
...
stack[0]->s = 'a';
stack[0]->lineNum = 1;

但要注意:您需要为stack中的每个项目分配内存。 stack包含100个指向struct item的指针,但每个指针都包含垃圾(它们都指向无效的内存)。

对于stack中的每个元素,您需要像stack[n] = malloc(sizeof struct item)一样分配内存。

答案 2 :(得分:1)

struct item stack[100]是你想要的代码所需要的。你拥有的是一系列指针,如果你想使用它们,你需要在声明之前分配。

答案 3 :(得分:1)

您尚未定义struct item。您目前有一个名为item的匿名struct变量。您似乎忘了包含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.

答案 4 :(得分:0)

stacks不是item的数组,它是指向item s 的指针数组,所以在尝试使用之前需要取消引用它们它们:

(*(stack[0])).s = 'a';
(*(stack[0])).lineNum = 1;