碰到access violation

myh0305 2004-12-12 10:49:28
#include <iostream.h>

typedef struct
{
int* array;
int sp;
int size;
}StackStruct;

class Queue {
public:
void Init(StackStruct *s, int size);
void cleanUp();
int isEmpty(StackStruct *s);
int isFull(StackStruct *s);
void push(int item);
int pop(StackStruct *s);

public:
StackStruct *s;
};

void Queue::Init(StackStruct *s, int size)
{
s->array = new int[size];
s->size = size;
s->sp = 0;
}

void Queue::cleanUp()
{
delete s->array;
}

int Queue::isEmpty(StackStruct *s)
{
return s->sp == 0 ? 1 : 0;
}

int Queue::isFull(StackStruct *s)
{
return s->sp == s->size ? 1 : 0;
}

void Queue::push(int item)
{
if(!isFull(s)) s->array[s->sp++] = item;
}

int Queue::pop(StackStruct *s)
{
if(isEmpty(s))
return 0;
else
return s->array[--s->sp];
}

void main()
{
Queue queue;
StackStruct *stack =queue.s;
queue.Init(stack, 15);

for(int i=0; i < 25; i++)
queue.push(i);
while(!queue.isEmpty(stack))
cout<<queue.pop(stack)<<" ";
cout<<endl;
}

执行到s->array = new int[size];语句时出错,为access violation
请高手指点.
...全文
81 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
myh0305 2004-12-13
  • 打赏
  • 举报
回复
谢谢上的各位!
kissinger2000 2004-12-13
  • 打赏
  • 举报
回复
#include <iostream.h>

typedef struct
{
int* array;
int sp;
int size;
}StackStruct;

class Queue {
public:
void Init( int size);
void cleanUp();
int isEmpty();
int isFull();
void push(int item);
int pop();

public:
StackStruct *s;
};

void Queue::Init( int size)
{
s = new StackStruct;
s->array = new int[size];
s->size = size;
s->sp = 0;
}

void Queue::cleanUp()
{
delete s->array;
}

int Queue::isEmpty()
{
return s->sp == 0 ? 1 : 0;
}

int Queue::isFull()
{
return s->sp == s->size ? 1 : 0;
}

void Queue::push(int item)
{
if(!isFull()) s->array[s->sp++] = item;
}

int Queue::pop()
{
if(isEmpty())
return 0;
else
return s->array[--s->sp];
}

void main()
{
Queue queue;
//StackStruct *stack =queue.s;
queue.Init( 15);

for(int i=0; i < 25; i++)
queue.push(i);
while(!queue.isEmpty())
cout<<queue.pop()<<" ";
cout<<endl;
}
liem 2004-12-13
  • 打赏
  • 举报
回复
void Queue::Init(StackStruct *s, int size)
{
s->array = new int[size];
s->size = size;
s->sp = 0;
}
1)由于StackStruct *s是Queue的成员,因此不必作为Queue::Init的参数,其它成员函数也是如此
2)Queue没有定义构造函数,因此将调用默认的构造函数,而在默认的构造函数中,没有为StackStruct *s分配空间,因此需要在Init中为s分配空间


void Queue::Init(int size)
{
s=new StackStruct;
s->array = new int[size];
s->size = size;
s->sp = 0;
}

021850524 2004-12-13
  • 打赏
  • 举报
回复
Queue queue;这句中的queue没有构造齐吧.queue.s还没有分配空间呢你就使用它了.
beyondtkl 2004-12-13
  • 打赏
  • 举报
回复
StackStruct *s;

先 s = new StackStruct...

Queue queue; 你這個queue.s 沒有分配空間呀。。。是傳說重的野指針。。。。
myh0305 2004-12-13
  • 打赏
  • 举报
回复
高手帮忙看一下 啊!
wugu111 2004-12-12
  • 打赏
  • 举报
回复
我喜欢一楼
呵呵

64,683

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧