为什么我重载的 << 运算符没有输出最后一行?
Why is my overloaded << operator not outputting the last line?
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”以查看它是否可以打印任何东西,但没有骰子。
如果有人需要查看更多代码,我很乐意提供!
在你的循环中,当你到达最后一个元素时,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;
}
...
}
rowPoint = rowPoint->nextRow;
point = rowPoint->firstInRow;
rowPoint
最终会 return 一个 nullptr
,而 point
将使用该无效指针访问 firstInRow
,这将使您的应用程序崩溃并且代码 os << "0 0 0" << endl;
永远不会被执行。或者 nextRow
永远不会 return 为空(因此你的循环永远不会结束)。
解决方案:
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;
}
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”以查看它是否可以打印任何东西,但没有骰子。
如果有人需要查看更多代码,我很乐意提供!
在你的循环中,当你到达最后一个元素时,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;
}
...
}
rowPoint = rowPoint->nextRow;
point = rowPoint->firstInRow;
rowPoint
最终会 return 一个 nullptr
,而 point
将使用该无效指针访问 firstInRow
,这将使您的应用程序崩溃并且代码 os << "0 0 0" << endl;
永远不会被执行。或者 nextRow
永远不会 return 为空(因此你的循环永远不会结束)。
解决方案:
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;
}