【问题标题】:Why am I getting errors in my stack data structure?为什么我的堆栈数据结构中出现错误?
【发布时间】:2021-10-01 13:33:42
【问题描述】:

我决定使用 C 创建一个堆栈。我刚刚为 push 函数编写了代码,现在我遇到了错误(它说我的 maxsize 有问题)。

如果你问我,一切似乎都刚刚好,我不知道错误可能是什么。

#include <stdio.h>
#include <stdlib.h>

#define maxsize 100;

int top=-1, item;
int s[maxsize];

void push()
{
    if (top == maxsize-1)
    {
        printf("Stack overflow\n");
        return;
    }

    top = top + 1;
    s[top] = item;
}

我得到的错误是:-

stack.c:3:20: error: expected ']' before ';' token
#define maxsize 100;
               ^
stack.c:5:7: note: in expansion of macro 'maxsize'
int s[maxsize];
  ^~~~~~~
stack.c: In function 'push':
stack.c:3:20: error: expected ')' before ';' token
#define maxsize 100;
               ^
stack.c:9:16: note: in expansion of macro 'maxsize'
if (top == maxsize-1)
           ^~~~~~~
stack.c:9:8: note: to match this '('
if (top == maxsize-1)
   ^
stack.c:16:5: error: 's' undeclared (first use in this function)
s[top]=item;
^
stack.c:16:5: note: each undeclared identifier is reported only once
for each function it appears in

【问题讨论】:

  • 能否请您发布错误输出?

标签: c data-structures stack


【解决方案1】:

使用此代码:

#include <stdio.h>
#include <stdlib.h>

#define maxsize 100

int top=-1,item;
int s[maxsize];

void push()
{
    if (top == maxsize-1)
    {
        printf("Stack overflow\n");
        return;
    }

    top = top + 1;
    s[top] = item;
}

在这里,您在导致问题的#define 语句之后使用了;

【讨论】:

  • 或许能解释一下为什么会导致这个问题?请通过editing (changing) your answer 回复,而不是在 cmets 中(without "Edit:"、"Update:" 或类似的 - 答案应该看起来像是今天写的)。
  • 好的,谢谢你的建议。我会做的。
【解决方案2】:

#define 指令不以; 结尾。改为#define maxsize 100

【讨论】:

  • 这通常不是真的。也许有资格你的陈述?请通过editing (changing) your answer 回复,而不是在 cmets 中(without "Edit:"、"Update:" 或类似的 - 答案应该看起来像是今天写的)。
猜你喜欢
  • 2020-10-10
  • 1970-01-01
  • 2015-11-15
  • 2021-06-18
  • 2020-06-28
  • 2018-06-02
  • 2019-01-09
  • 2021-09-05
  • 1970-01-01
相关资源
最近更新 更多