为什么我的重载<<操作员不输出最后一行?

时间:2016-03-05 17:13:15

标签: c++ linked-list operator-overloading

ostream& operator<< (ostream& os,SparseMatrix& m)
{
RowNode* rowPoint = m.rowFront;
Node* point = rowPoint->firstInRow;


while(rowPoint != NULL)
    {
    while (point != NULL)
        {
        os << point->row;
        os << ' ';
        os << point->column;
        os << ' ';
        os << point->data;
        os << endl;
        point = point->right; 
        }
    rowPoint = rowPoint->nextRow;
    point = rowPoint->firstInRow;
    }

os << "0 0 0" << endl;

return os;
}

当我尝试在我的程序中运行它时,列表完全正确,但最后的“0 0 0”行永远不会出现。我尝试过不同的格式化,将它放在较大的while循环结束时的if语句中,我甚至尝试输出一堆不仅仅是“0 0 0”来查看它是否可以打印任何内容,但是没有骰子。

如果有人需要查看更多代码,我很乐意提供它!

2 个答案:

答案 0 :(得分:1)

在你的循环中,当你到达最后一个元素时,rowPoint将被设置为NULL rowPoint = rowPoint->nextRow;

不幸的是,在下一个语句中检查它是否为空之前,你取消引用这个空指针:

point = rowPoint->firstInRow;

这会导致UB。

要解决它,请稍微更改一下代码:

ostream& operator<< (ostream& os,SparseMatrix& m)
{
RowNode* rowPoint = m.rowFront;

while(rowPoint != NULL)
    {
    Node* point = rowPoint->firstInRow;  // here you're sure not to dereference NULL ptr
    while (point != NULL)
        {
        ...
        point = point->right; 
        }
    rowPoint = rowPoint->nextRow;
    }
...
}

答案 1 :(得分:1)

rowPoint = rowPoint->nextRow;
point = rowPoint->firstInRow;

rowPoint最终将返回nullptr,而point将使用该无效指针访问firstInRow,这将使您的应用崩溃并且代码{{1}绝不会被执行。或许os << "0 0 0" << endl;永远不会返回null(因此你的循环永远不会结束)。

解决方案:

nextRow
相关问题