所以,我正在用 C 语言开发一个带有 push、pop 等的标准堆栈程序。代码编译良好,但一旦我运行它,它就会崩溃并显示"停止工作"消息。我正在Windows系统上开发开发C++应用程序。代码给出如下:
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct stack {
int items[MAX];
int top;
};
typedef struct stack st;
void createemptyStack(st *s) {
s->top = -1;
}
int isEmpty(st *s) {
if (s->top == -1)
return 1;
else
return 0;
}
int isFull(st *s) {
if (s->top == MAX - 1)
return 1;
else
return 0;
}
int push(st *s) {
int newitem;
printf("Enter the value you want to push");
scanf("%d", &newitem);
if (isFull(s)) {
printf("Stack is full");
} else {
s->top++;
s->items[s->top] = newitem;
}
}
void pop(st *s) {
if (isEmpty(s)) {
printf("Stack is empty");
} else {
printf("Items popped %d", s->items[s->top]);
s->top--;
}
}
int main() {
int ch;
int loop = 1;
st *s;
createemptyStack(s);
do {
printf("n ***STACK OPERATIONS");
printf("n 1. PUSH");
printf("n 2. POP");
printf("n 3. EXIT");
printf("n ***************");
printf("n Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
push(s);
break;
case 2:
pop(s);
break;
case 3:
printf("Visit again");
loop = 0;
exit(0);
default:
printf("Invalid choice");
}
} while(loop);
getch();
}
如果你能在这件事上帮助我,对我真的很有帮助。我认为问题可能存在于do / while
循环中,但我不确定。想对此事发表一些意见。
st *s;
您没有将内存分配给*s
, 将其更改为
st *s = malloc(sizeof(*s));
或
st s;
createemptyStack(&s)
作为指向st
的指针的s
的值未初始化,因此包含垃圾数据。现在,当您将s
传递给createemptyStack
时,它会尝试访问垃圾数据指向的内存位置,s
从而导致分段错误。 首先需要通过定义结构对象为结构分配空间
st obj;
st* s = &obj;
或通过动态内存分配
s = malloc(sizeof(st))
s
被定义为指向堆栈对象的指针。您需要一个实际的struct stack
对象供s
指向。要么将一个定义为局部变量:
st obj;
st *s = &obj;
或者从堆中分配一个:
st *s = malloc(sizeof(*s));
if (s == NULL) {
fprintf(stderr, "allocation failuren");
exit(1);
}