顺序栈初始化遇到的问题(代码有,不过出错)

来源:百度知道 编辑:UC知道 时间:2024/05/09 06:20:31
有人能帮我看看如下代码吗?
typedef struct info{
int number;/*车牌号*/
int time;/*进入或离开的时间*/
}info;

typedef struct Stack{
info *base;
info *top;
int stacksize;
}Stack;

void InitStack(Stack s, int n)/*初始化栈*/
{
s.base = (info *)malloc(n * sizeof(info));
if(!s.base)
exit(overflow);
s.top = s.base;
s.stacksize = n;
}

void Push(Stack s, int x, int y)/*插入栈顶元素*/
{
if(s.top - s.base >= s.stacksize)
{
printf("停车场已满\n");
exit(overflow);
}
s.top++;
s.top->number = x;
s.top->time = y;
}
就是这两个初始化的函数,为什么x和y的值无法送给相应的结构体呢,谢谢了

作为一个栈的压栈,最好是用成员函数,就是写在那个结构体内部.不知道你学C++了没.
你那么写那个stack,作为临时的变量了.所以会失败,你那么写也可以用指针.
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define overflow 1
typedef struct info{
int number;/*车牌号*/
int time;/*进入或离开的时间*/
}info;

typedef struct Stack{
void InitStack(int n);
void Push(int x,int y);
info *base;
info *top;
int stacksize;
}Stack;

void Stack::InitStack(int n)/*初始化栈*/
{
base = (info *)malloc(n * sizeof(info));
if(! base)
exit(overflow);
top = base;
stacksize = n;
}

void Stack::Push(int x, int y)/*插入栈顶元素*/
{
if(top - base >= stacksize)
{
printf("停车场已满\n");
exit(overflow);
}
top++;
top->number = x;
top->time = y;
}

void main()
{
Stack s;
s.InitStack(10);
s.Push(1