奇怪的C++指针声明

 陪你浪迹天涯萱萱 发布于 2023-01-01 21:55

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

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;
    }
}

此代码可以编译和运行,没有任何错误消息!唯一的区别是声明.这很奇怪,至少对我而言.

任何人都可以想出一个主意吗?

2 个回答
  • Vertex* temp1, *temp2 = graph->adjacentList[i];
    

    相当于

    Vertex *temp1;
    Vertex *temp2 = graph->adjacentList[i];
    

    你可以看到为什么有一个错误说temp1没有初始化.

    2023-01-01 22:00 回答
  • 在此代码段中:

    Vertex* temp1, *temp2 = graph->adjacentList[i];
    

    你实际上并没有初始化temp1.

    考虑以下:

    int a, b = 2;
    

    什么是a?它不是2,它是未初始化的.你的第二个实现更正确.

    2023-01-01 22:02 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有