我正在编写一个关于深度优先搜索算法的非常小的程序。在程序结束时,需要删除内存。
for(int i = 0; i < V; i++) {
Vertex* temp1, *temp2 = graph->adjacentList[i];
while(temp1 != NULL) {
temp2 = temp1->next;
delete temp1;
temp1 = temp2;
}
}
此代码删除图形的相邻列表。代码可以编译运行,但是 运行时错误。错误信息是
The variable 'temp1' is being used without being initialized.
请看另一段代码:
for(int i = 0; i < V; i++) {
Vertex* temp1 = graph->adjacentList[i];
Vertex* temp2 = graph->adjacentList[i];
while(temp1 != NULL) {
temp2 = temp1->next;
delete temp1;
temp1 = temp2;
}
}
这段代码可以编译运行,没有任何错误提示! 唯一的区别是声明。这很奇怪,至少对我来说是这样。
谁能想出点子?
最佳答案
Vertex* temp1, *temp2 = graph->adjacentList[i];
相当于
Vertex *temp1;
Vertex *temp2 = graph->adjacentList[i];
您可以看到为什么会出现错误,提示 temp1
未初始化。
关于c++ - 奇怪的 C++ 指针声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24858291/