You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否创建struct node类型数组?下述代码实现逻辑是否可行?

关于struct node数组的创建与代码逻辑分析

当然可以创建struct node类型的数组啦!不过你的代码里藏着一个容易踩坑的问题,先帮你拆解清楚:

1. 能不能创建struct node类型的数组?

完全没问题!常见的实现方式有两种:

  • 静态数组:如果元素数量是编译期就能确定的固定值,可以直接声明:
    struct node arr[10]; // 固定大小为10的node数组
    
  • 动态数组:如果元素数量是运行时才确定的(比如你代码里的numOfLanding),可以用动态内存分配,或者更省心的标准容器std::vector。

2. 你的代码逻辑存在什么问题?

你写的struct node *arr[numOfLanding];是一个指针数组——数组里的每个元素都是指向struct node的指针,但这些指针并没有被初始化(没有指向有效的内存空间),直接用arr[i]->hour=hour;会触发未定义行为(比如程序崩溃、输出乱码等)。

两种修正方案:

方案一:直接创建struct node的动态数组

把指针数组改成struct node类型的动态数组,用new分配内存:

struct node { int hour; int minutes; };
int main() {
    int numOfLanding, minGap, hour, minutes;
    cin>>numOfLanding;
    cin>>minGap;
    cout<<endl;
    // 分配node类型的动态数组
    struct node *arr = new struct node[numOfLanding];
    for (int i=0; i<numOfLanding; i++) {
        cin>>hour;
        cin>>minutes;
        arr[i].hour = hour; // 用.访问成员,因为arr[i]是node对象而非指针
        arr[i].minutes = minutes;
    }
    // 记得用完后释放内存,避免内存泄漏
    delete[] arr;
    return 0;
}

方案二:使用std::vector(更推荐,无需手动管理内存)

C++里优先用标准容器,vector会自动处理内存的分配与释放,代码更安全简洁:

#include <vector> // 需要包含头文件
struct node { int hour; int minutes; };
int main() {
    int numOfLanding, minGap, hour, minutes;
    cin>>numOfLanding;
    cin>>minGap;
    cout<<endl;
    // 创建包含numOfLanding个node对象的vector
    std::vector<struct node> arr(numOfLanding);
    for (int i=0; i<numOfLanding; i++) {
        cin>>hour;
        cin>>minutes;
        arr[i].hour = hour;
        arr[i].minutes = minutes;
    }
    // 无需手动释放内存,vector会在生命周期结束时自动清理
    return 0;
}

补充:如果一定要用指针数组?

那你需要给每个指针单独分配内存,比如在循环里加arr[i] = new struct node;,用完后还要逐个释放每个指针的内存,这种方式繁琐且容易漏释放,一般不推荐。

内容的提问来源于stack exchange,提问作者Nicholas Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:49:36