【问题标题】:Why is my temporary pointer's next changing from null to some other garbage?为什么我的临时指针的下一个从 null 变为其他垃圾?
【发布时间】:2015-01-20 23:27:39
【问题描述】:

我将队列实现为链表,并试图了解值类型和引用类型之间的区别。因此,我将front 作为值类型,将rear 作为引用类型,因为它需要在每次迭代时指向某个节点。

在插入 2 个元素 1 和 2 时,rearnext 指向 NULL。但是当我尝试显示时,第一次迭代时,节点 2 的 nextNULL。但是在第二次迭代中,在执行temp = temp->next 时,它指向了一些垃圾值。请帮我解决这个问题。

// Queue implementation
#import "iostream"
#import "queue.h"
using namespace std;

queue queue::insert(int num)
{
    node newnode(num);
    if (front.x == NULL)
    {
        front = newnode;
        rear = &front;
    }
    else
    {
        rear->next = &newnode;
        rear = &newnode;
    }

    //cout<<"inserted"<<"\n";
    return *this;
}

void queue::display()
{
    node* temp = &(this->front);
    int i = 0;
    while (temp != NULL)
    {
        cout << temp->x << "\n";
        temp = temp->next;
    }
}

// Queue.h
#import "node.h"
class queue
{
public:
    node front;
    node* rear;
    queue insert(int num);
    void remove(int num);
    void display();
};

【问题讨论】:

  • 使用调试器逐行检查代码可能有助于诊断问题。
  • 您没有提供node 类的实现,这会很有帮助。还有一个建议,如果您是using namespace std;,请不要使用queue 作为您的数据类型的名称,您知道std::queue 存在并且可能会发生冲突,对吧?
  • 你用错了术语:rear 不是指针,它不是参考。
  • 我使用了调试器,但无法找出问题所在。所以在这里发布。为什么会有这么多的负面影响?这个问题有那么糟糕吗?

标签: c++ pointers reference linked-list singly-linked-list


【解决方案1】:

您的指针最终指向垃圾,因为node newnode(num); 在堆栈上实例化了一个对象,该对象在函数返回后立即消失。

【讨论】:

  • 但是前两个值打印正确。如果是这样的话,一切都必须是垃圾吧?
  • 不,你处于未定义行为的领域,这意味着任何事情都可能发生,包括它可能看起来有效。
猜你喜欢
  • 2015-07-03
  • 2021-02-20
  • 2011-08-22
  • 2015-11-16
  • 2014-05-08
  • 2022-12-04
  • 2023-03-31
  • 2011-08-24
  • 2013-03-03
相关资源
最近更新 更多