今天学队列时发现了一个问题记录一下
先放正确代码
#include<iostream>
using namespace std;
typedef int Elemtype;
#define MAX 10
typedef struct{
Elemtype Data[MAX];
int rear;
int front;
}Queuearry,* Qarry;
class Queue{
public:
void InitQueue(Qarry S);
int PushQueue(Qarry S,Elemtype x);
int PopQueue(Qarry S,Elemtype *x);
};
void Queue::InitQueue(Qarry S)
{
S->front = -1;
S->rear = -1;
}
int Queue::PushQueue(Qarry S,Elemtype x)
{
if(S->rear==MAX-1)
return 0;
else{
S->Data[++S->rear] = x;
return 1;
}
}
int Queue::PopQueue(Qarry S,Elemtype *x)
{
if(S->front==S->rear)
{
return 0;
}
else
{
*x = S->Data[++S->front];
return 1;
}
}
int main()
{
Qarry S = new Queuearry;
int x;
Queue w;
w.InitQueue(S);
cout<<S->front<<endl;
w.PushQueue(S,1);
w.PushQueue(S,1);
w.PushQueue(S,1);
w.PushQueue(S,1);
w.PopQueue(S,&x);
for(int i=S->front+1;i<=S->rear;i++)
{
cout<<S->Data[i]<<endl;
}
return 0;
}
开始时没有new一个空间它调试的时候报了这样一个错
这是由于我对空指针赋值了。
所以我需要创建一个空间。
那么如果我这样做呢
他会不会报这样的错呢 。
答案是不会,因为这时候编译器会为我们申请一个空间存放在栈区。