c++ - 奇怪的 C++ 指针声明

标签 c++ pointers declaration

我正在编写一个关于深度优先搜索算法的非常小的程序。在程序结束时,需要删除内存。

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/

相关文章:

c - 指向指针数组的指针指向意外的地址

c - 使用指针对函数(下图)进行单元测试

c++ - for循环中的产品序列

c++ - C 和 C++ 的优化工具

objective-c - 分配指针 - Objective-C

java - 使用抽象类实现接口(interface)时要声明什么(不)?

c - "int *p =0;"和 "int *p; *p=0;"有什么区别

c++ - 我可以扩展一个参数包并用它定义一个参数列表吗?

c++ - 在保存到 RAD Studio 之前获取修改后的文件

c - 为什么 "volatile"只要求数组声明定义一致性?