[英]Stack code in C crashes and stops working as soon as it is run
因此,我正在使用C的push,pop等來開發標准堆棧程序。代碼可以很好地編譯,但是一旦我運行它,它就會崩潰並顯示“停止工作”消息。 我正在Windows系統上開發Dev 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
的垃圾數據所指向的內存位置,從而導致分段錯誤。 首先,您需要通過定義struct對象來為結構分配空間
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 failure\n");
exit(1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.