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

时间:2015-01-11 17:11:25

标签: c++ pointers if-statement null

我在队列中尝试将C程序作为链接列表。每当我尝试执行时,如果条件比较指针(在这种情况下为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);
}

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

1 个答案:

答案 0 :(得分:4)

您永远不会初始化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()等人