我正在嘗試使用指針和結構實現堆棧推送和彈出操作。這段代碼在第40行給出錯誤(s->entry=(StackEntry *)malloc(sizeof(StackEntry)*(n+1));
),說段錯誤。請幫助使用指針實現堆棧
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
typedef long int StackEntry ;
typedef int Boolean;
typedef struct stack{
int top;
int size;
StackEntry *entry; //pointer to dynamic array
}Stack;
Boolean StackEmpty(Stack *s)
{
return s->top<=0;
}
Boolean StackFull(Stack *s)
{
return s->top >= s->size;
}
void Error(char *msg)
{
puts(msg);
}
int StackSize(Stack *s)
{
return s->top ;
}
void StackTop(StackEntry *item,Stack *s)
{
*item=s->entry[s->top];
}
void CreateStack(Stack *s,int n)
{
s->top=0;
s->size=n;
s->entry=(StackEntry *)malloc(sizeof(StackEntry)*(n+1));
}
void Push(StackEntry item,Stack *s)
{
if(StackFull(s))
Error("Stack is full");
else s->entry[s->top++]=item;
}
int main() {
int n;
scanf("%d",&n);
Stack *s;
CreateStack(s,n);
Push(10,s);
//Push(15,s);
return 0;
}
你檢查的'N' –
'創建堆棧(S,N)的值;'此使用未初始化的變量's'。 – BLUEPIXY
'Stack * s = malloc(sizeof(Stack));' –