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

标签 c++ pointers if-statement null

我正在尝试将 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/

相关文章:

c++ - 是否可以将可变参数宏字符串化为逗号分隔的字符串列表?

c++ - 如何转换(指针 vector )-->(指向指针数组的指针)

c - 当存储非指针值时,C 中实际上发生了什么?

javascript - Screeps autospawner 不工作 'totally'

macos - Swift if 语句不返回值

postgresql - "IF"处或附近的语法错误 PostgreSQL

c++ - 为什么在函数内部初始化时 C++ 对象会被破坏?我能做些什么来防止它?

c++ - STL中有没有像std::unique这样的算法来存储相等对象的数量?

c++ - constexpr 函数不在编译时计算值

c - 为什么在内核代码中一些变量的地址存储在char指针中?