请大家帮我看看哪里出了问题
这是一个栈的基本操作的程序,可是为什么运行不了?跳出一个这个程序已停止工作的窗口?
#include<stdio.h>
#include<stdlib.h>
#define STACKSIZE 100
typedef struct
{
int *base;
int *top;
}SqStack;
void InitStack(SqStack *s)
{
s->base=(int *)malloc(STACKSIZE *sizeof(int));
if(s->base)
{
printf("memory is not enough!");
return;
}
s->top=s->base;
}
void DestroyStack(SqStack *s)
{
free(s->base);
s->top=s->base=NULL;
}
int StackEmpty(SqStack s)
{
return s.top==s.base;
}
int GetTop(SqStack s,int *e)
{
if(StackEmpty(s))
{
printf("\nthe stack is empty!");
return -1;
}
*e=*(s.top-1);
return 1;
}
int GetLength(SqStack s)
{
return s.top-s.base;
}
void Push(SqStack *s,int e)
{
if(s->top-s->base>=STACKSIZE)
{
printf("stack is full");
}
*s->top++=e;
}
int Pop(SqStack *s,int *e)
{
if(StackEmpty(*s))
{
printf("\nthe stack is empty");
return -1;
}
*e=*--s->top;
return 1;
}
main()
{
SqStack s;int i,e,n=5;
InitStack(&s);
printf("\nInput %d numbers for STACK:",n);
for(i=1;i<=n;i++)
{
scanf("%d",&e);
Push(&s,e);
}
i=GetTop(s,&e);
printf("\n the top element is:%d",e);
printf("\n Pops,print all elements:\n");
n=GetLength(s);
for(i=1;i<=n;i++)
{
Pop(&s,&e);
printf("%4d",e);
}
DestroyStack(&s);
printf("\n");
}
[解决办法]
s->base=(int *)malloc(STACKSIZE *sizeof(SqStack));//问题1
[解决办法]
还有一个概念你要搞清楚,你malloc出来的空间是在堆上面的,是向高地址发展的空间。
你要模拟栈,切不可以往低地址空间扩展,所以按道理在栈满的情况下,top应该在你malloc分配地址的首地址,这样的话,感觉你的代码是不是完全不对了?
[解决办法]
void InitStack(SqStack *s){ s->base=(int *)malloc(STACKSIZE *sizeof(int)); if(s->base == NULL) { printf("memory is not enough!"); return; } s->top=s->base;}
[解决办法]
修改好的程序
#include<stdio.h>#include<stdlib.h>#define STACKSIZE 100typedef struct{ int *base; int *top;}SqStack;void InitStack(SqStack *s){ s->base=(int *)malloc(STACKSIZE *sizeof(int)); if(s->base==NULL) { printf("memory is not enough!"); return; } s->top=s->base;}void DestroyStack(SqStack *s){ free(s->base); s->top=s->base=NULL;}int StackEmpty(SqStack s){ return s.top==s.base;}int GetTop(SqStack s,int *e){ if(StackEmpty(s)) { printf("\nthe stack is empty!"); return -1; } *e=*(s.top-1); return 1;}int GetLength(SqStack s){ return s.top-s.base;}void Push(SqStack *s,int e){ if(s->top-s->base>=STACKSIZE) { printf("stack is full"); } *s->top++=e;}int Pop(SqStack *s,int *e){ if(StackEmpty(*s)) { printf("\nthe stack is empty"); return -1; } *e=*--s->top; return 1;}void main(){ SqStack s;int i,e,n=5; InitStack(&s); printf("\nInput %d numbers for STACK:\n",n); for(i=1;i<=n;i++) { scanf("%d",&e); Push(&s,e); } i=GetTop(s,&e); printf("\n the top element is:%d",e); printf("\n Pops,print all elements:\n"); n=GetLength(s); for(i=1;i<=n;i++) { Pop(&s,&e); printf("%4d",e); } DestroyStack(&s); printf("\n");}
[解决办法]