gpt4 book ai didi

c - 未能在 C 中实现一个非常简单的堆栈数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:48:40 27 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
static int top = 0;
static char stack[100];

void push(char thing2push)
{
if (top == 100){
fprintf(stderr, "Too many things in the stack");
exit(1);
}else{
stack[top] = thing2push;
top++;
}
}

然后我主要有:

 extern void push(int);
push(1);

但这会导致“段错误”。我猜它与内存违规有关,但我不知道如何修复它。

编辑这是完整的代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
extern int pop();
extern void push(int);

void readTag(){
int tagVal = getchar();
int poppedVal;
if (getchar() == '/'){
poppedVal = pop();
if (poppedVal != tagVal){
printf("NOT Valid");
exit(1);
}
}else{
push(1);
}

}


int main(int argc, char * argv[])
{
int ch;
while ((ch = getchar()) != EOF) {
if (!(isalpha(ch) || ch == '<'))
continue;
readTag();
}
printf("Valid");
exit(0);
}

这是堆栈:

#include <stdio.h>
#include <stdlib.h>
static int top = 0;
static char stack[100];

int isEmpty()
{
return !(top);
}

char pop()
{
if (isEmpty()){
fprintf(stderr, "Stack is empty");
exit(1);
}
top--;
return stack[top+1];
}

void push(char thing2push)
{
if (top == 100){
fprintf(stderr, "Too many things in the stack");
exit(1);
}else{
stack[top] = thing2push;
top++;
}
}

最佳答案

top 变量始终指示堆栈中的next 条目(就​​您的程序而言,它显然不包含有效元素)。所以你不应该读取 stack[top] 的值。

函数pop发生段错误,当top达到100时:

top--;               // top == 99
return stack[top+1]; // return stack[100]

您应该写入 stack[top],但从 stack[top-1] 读取。

您可以保留函数 push 不变,只更改函数 pop:

top--;
return stack[top];

关于c - 未能在 C 中实现一个非常简单的堆栈数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22356733/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com