为什么会出现错误?

Why the errors?

# include <stdio.h>
# include <stdlib.h>
#define MAX 1000
struct stack { 
    int st[MAX];
    int *top ; 
};  

int main() {  
  struct stack *s = malloc(sizeof(struct stack));
  s->(*top) = -1;
  return 0;
}

我正在用 C 编写一段用于堆栈实现的代码。这是一个练习作业。为什么会出现以下编译错误?

错误:需要标识符 s->(*top) = -1;

错误:使用了未声明的标识符 'top' s->(*top) = -1;

如果你想将 -1 赋给指针:s->top = -1;(应该给出警告但可能会编译)。

如果要将 -1 分配给 int top 指向 *(s->top) = -1; 将编译但可能会崩溃,因为 top 尚未指向任何有效的地方。

int anInteger;
struct stack *s = malloc(sizeof(struct stack));
s->top = &anInteger;
*(s->top) = -1;
/* anInteger should now have the value -1 */
/* beware scope - if you did this somewhere other than main
   anInteger may go out of scope */
return 0;

我知道您已经接受了这个问题的答案,但是根据您的变量名称,我认为您真正想要做的是:

s->top = s->st;

这意味着 "top" 指向堆栈的位置 0,您可以在顶部插入然后递增,如下所示:

*(s->top) = INSERT_VALUE;
s->top++;

弹出:

REMOVE_VALUE = *(s->top);
s->top--;

两者都没有任何绑定检查。鉴于您已将 top 声明为指针,这就是我认为您想要做的。您通常不会将空指针存储为 -1,而是将它们存储为 0(或 NULL)。也就是说,在这种情况下使用空指针没有任何意义。