C++程序在使用 if 条件检查指针是否为 NULL 时崩溃
C++ program crashes while checking if a pointer is NULL using if condition
我正在队列上尝试将 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()
等人。
相关文章:
- std::vector::迭代器是否可以合法地作为指针
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 返回指向对象的指针的函数调用是否为 prvalue?
- 对象初始化中是否允许指向此成员的指针?
- 新分配指向函数的指针是否合法?
- 在函数结束后使用指向变量的指针是否安全?
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 如果整数与指针大小相同,则重新解释将整数转换为指针双射是否具有双射作用?
- 是否可以使用函数指针调用虚拟析构函数?
- std::less是否应该允许在编译时比较不相关的指针?
- 是否允许编译器省略对指针的 &* 运算符的组合调用?
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 检查输入 std::array 指针数据是否等于某个常量数组
- 成员访问是否在空指针上定义C++?
- 如果只有 std::auto_ptr 可用,我是否仍应该使用智能指针?
- 是否可以使用指针访问变量以避免直接编辑变量?
- 是否可以仅通过将分配的指针地址存储在C++中来分析内存?
- "this"指针的值在对象的生存期内是否恒定?