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

C++ program crashes while checking if a pointer is NULL using if condition

本文关键字:是否 指针 NULL 崩溃 检查 条件 程序 if C++      更新时间:2023-10-16

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

struct node
{
    int info;
    node *next;
};
struct que
{
    struct node *front
    struct node *rear;
    
    que() { front = rear = NULL; }
};
struct que *pq;
/* prototypes */
void Displace(struct que *q);
int Empty(struct que *q);
void Insert(struct que *q,int x);
void Delete(struct que *q);
int main()
{
    int cho;
    while(1)
    {
        printf("Enter 1 to insert in a queuen");
        printf("Enter 2 to delete in a queuen");
        printf("Enter 3 to display the queuen");
        scanf("%d", &cho);
        if (cho == 1)
        {
            int x;
            printf("Enter the info to be addedn");
            scanf("%d",&x);
            Insert(pq, x);
        }
        else if (cho == 2)
            Delete(pq);
        else if (cho == 3)
            Displace(pq);
    }
    return 0;
}
int Empty(struct que *q) 
{
    return ((q-> front == NULL) ? 1 : 0); //Error
}
void Insert(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 addedn");
}
void Delete(struct que *q)
{
    node *p = NULL;
    if (Empty(q))
    {
        printf("Empty queue.Insert some elementsn");
        return;
    }
    p = q->front;
    q->front = p->next;
    delete p;
    printf("Node deletedn");
}
void Displace(struct que *q)
{
    if (Empty(q))
    {
        printf("Empty queue.Insert some elementsn");
        return;
    }
    node *i = NULL;
    for (i = q->front; i != NULL; i = i->next)
        printf("%dn", i->info);
}

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

你从不初始化pq,所以下面的q->rear具有未定义的行为:

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

解决此问题的一种方法是将

struct que *pq;

struct que pq;

然后将&pq传递给Insert()等人。