gpt4 book ai didi

C++ 程序在使用 if 条件检查指针是否为 NULL 时崩溃

转载 作者:太空狗 更新时间:2023-10-29 20:58:19 27 4
gpt4 key购买 nike

我正在尝试将 C 程序作为链表放在队列上。每当我尝试执行时,只要遇到 if 条件将指针(在本例中为 q->f)与 NULL 进行比较,它就会崩溃。请检查以下代码:

#include<stdio.h>
using namespace std;
struct node
{
int info;
node *next;
};
struct que
{
struct node *f; //front
struct node *r; //rear
que()
{
f=r=NULL; //initialize as NULL
}
};
struct que *pq;
/* prototypes */
void disp(struct que *q);
int emp(struct que *q);
void ins(struct que *q,int x);
void del(struct que *q);

int main()
{
int cho;
while(1) //so that it executes continuously and I can exit whenever I want
{
printf("Enter 1 to insert in a queue\n");
printf("Enter 2 to delete in a queue\n");
printf("Enter 3 to display the queue\n");
scanf("%d",&cho);
if (cho==1)
{
int x;
printf("Enter the info to be added\n");
scanf("%d",&x);
ins(pq,x);
}
else if (cho==2)
del(pq);
else if (cho==3)
disp(pq);
}
return 0;
}
int emp(struct que *q) // Check whether queue is empty or not
{
return ((q->f==NULL)?1:0); //Error
}
void ins(struct que *q,int a)
{
node *p;
p=new node;
p->info=a;
p->next=NULL;
if ((q->r)==NULL) //Error. I get crash and this statement is never executed.
(q->f)=p;
else
(q->r)->next=p;
(q->r)=p;
printf("Node added\n");
}
void del(struct que *q)
{
node *p=NULL;
if (emp(q))
{
printf("Empty queue.Insert some elements\n");
return;
}
p=q->f;
q->f=p->next;
delete p;
printf("Node deleted\n");
}
void disp(struct que *q)
{
if (emp(q))
{
printf("Empty queue.Insert some elements\n");
return;
}
node *i=NULL;
for (i=q->f;i!=NULL;i=(i)->next)
printf("%d\n",i->info);
}

我怀疑 if ((q->r)==NULL) 语句有问题。执行程序导致崩溃“已停止工作”。我也尝试用 if (!q->r) 替换它,但没有太大成功。我无法在我的代码中找到问题。请帮助我......谢谢

最佳答案

你永远不会初始化pq,所以下面的q->rundefined behaviour :

if ((q->r)==NULL)   //Error. I get crash and this statement is never executed.

解决这个问题的一种方法是转动

struct que *pq;

进入

struct que pq;

然后将&pq传递给ins()

关于C++ 程序在使用 if 条件检查指针是否为 NULL 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27889774/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com