2016-03-05 123 views
0
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”,以查看它是否可以打印任何内容,但是没有骰子。为什么我的重载<<运算符不输出最后一行?

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

+0

根据你的代码,如果'rowPoint'是NULL或'point'为NULL,则不会进行打印。我建议使用调试器和*观察*这两个变量。 –

回答

1

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

不幸的是,你解引用检查,如果它是NULL,在接下来的语句之前这个空指针:

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; 
    } 
... 
} 
+0

我只是在自己的问题上输入了一个答案,因为我在发布后立即发现了这个问题...... – Weesnork

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

rowPoint最终会返回一个nullptr,并且point将使用该无效的指针访问firstInRow,这将使您的应用程序崩溃和代码os << "0 0 0" << endl;将永远不会执行。或者也许nextRow永远不会返回null(因此你的循环永远不会结束)。

解决方案:

while (rowPoint != NULL) 
{ 
    point = rowPoint->firstInRow; 

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

    rowPoint = rowPoint->nextRow; 
}