august 发表于 2007-8-30 16:09:11

问下栈的问题


#include<stdio.h>
#define maxsize 100
typedef struct
{
    char stack;
    int top;
}stacktype;
void initstack(stacktype *s)      //初始化栈
{
    s->top=-1;
}
void push(stacktype *s,char x)   //入栈
{
    if(s->top==maxsize)
      printf("this is overflow\n");
    else
    {
      s->top++;
      s->stack=x;
    }
}
void pop(stacktype *s)      //出栈
{
    if(s->top==-1)
      printf("down overflow\n");
    else
      s->top--;
}
char gettop(stacktype *s)    //取栈顶元素
{
    if(s->top==-1)
      printf("this is null\n");
    else
      return(s->stack);
}
int empty(stacktype *s)      //   判断是否为空
{
    if(s->top==-1)
      return 1;
    else
      return 0;
}
void display(stacktype *s)         //显示栈中元素
{
    int i;
    printf("middle element :");
    for(i=s->top;i>=0;i--)
      printf("%c ",s->stack);
    printf("\n");
}
void main()
{
    stacktype *st;
    printf("build a inn\n");
    initstack(st);
    printf("inn null:%d\n",empty(st));
    printf("please insert element\n");
    push(st,'a');
    push(st,'b');
    push(st,'c');
    push(st,'d');
    display(st);
    printf("delete onetime\n");
    pop(st);
    printf("top element :%c\n",gettop(st));
    printf("delete onetime\n");
    pop(st);
    display(st);
}

为什么会报错呢?但是运行是可以的??

john_he 发表于 2007-8-30 16:43:29

是st没有初始化吧,经典错误。
你只定义了一个stacktype指针,没有给它分配内存。

august 发表于 2007-8-31 08:14:23

那是不是应该给个字符型的数组地址给它呢?

Zelsazgh 发表于 2007-8-31 08:50:22

stacktype *st=(stracktype*) malloc(sizeof(stacktype));
页: [1]
查看完整版本: 问下栈的问题