我正在编写一个关于深度优先搜索算法的小程序.在程序结束时,需要删除内存.
for(int i = 0; i < V; i++) { Vertex* temp1, *temp2 = graph->adjacentList[i]; while(temp1 != NULL) { temp2 = temp1->next; delete temp1; temp1 = temp2; } }
此代码删除图表的相邻列表.代码可以编译并运行但运行时错误.错误消息是
变量'temp1'正在使用而未初始化.
请看另一段代码:
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
没有初始化.
在此代码段中:
Vertex* temp1, *temp2 = graph->adjacentList[i];
你实际上并没有初始化temp1
.
考虑以下:
int a, b = 2;
什么是a
?它不是2
,它是未初始化的.你的第二个实现更正确.