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

如何从Linked List中提取指定行星数据并为程序变量赋值?

如何从行星链表中提取选中行星的数据?

首先,咱们先看看你代码里的几个关键问题:

  1. 错误的链表访问方式:SolarSystem是PlanetList_t*类型,也就是指向单个链表结构体的指针,不是数组,所以SolarSystem[PlanetNum]这种写法完全不对,会直接访问错误的内存地址,导致程序崩溃或者奇怪的行为。
  2. 成员访问层级错误:链表节点PlanetNode_t里的planet_Name才是指向Planet_t数据的指针,你直接写SolarSystem->head->Height是跳过了这个指针,肯定会出错——因为PlanetNode_t里根本没有Height这个字段!

接下来给你正确的实现方案,分两步走:

第一步:写一个辅助函数定位指定索引的行星节点

因为你是按索引(比如0=Pluto,1=Moon)切换行星,咱们可以写一个简单的遍历函数,找到对应索引的节点:

// 根据索引获取链表中的行星节点,索引从0开始
PlanetNode_t* get_planet_node(PlanetList_t* list, int index) {
    // 先做合法性检查:链表为空、索引越界都返回NULL
    if (list == NULL || index < 0 || index >= list->count) {
        printf("Error: Invalid planet index or empty list!\n");
        return NULL;
    }

    // 从表头开始遍历,走到目标索引的节点
    PlanetNode_t* current = list->head;
    for (int i = 0; i < index; i++) {
        current = current->next;
    }

    return current;
}

第二步:正确提取选中行星的数据

在main函数里,每次切换PlanetNum时,调用上面的函数找到节点,然后逐层访问行星数据:

// 假设PlanetNum是当前选中的行星索引(0到3)
PlanetNode_t* selected_node = get_planet_node(SolarSystem, PlanetNum);

// 必须先检查节点和行星指针是否有效,避免空指针崩溃
if (selected_node != NULL && selected_node->planet_Name != NULL) {
    // 正确提取每个字段:节点->行星指针->字段名
    double height = selected_node->planet_Name->Height;
    double velocity = selected_node->planet_Name->Velocity;
    double fuel = selected_node->planet_Name->Fuel;
    double gravity = selected_node->planet_Name->Gravity;
    double difficulty = selected_node->planet_Name->Difficulty;
    double fuelBurn; // 这里可以根据你的逻辑初始化或赋值

    // 现在这些变量就可以正常使用啦
    printf("Selected planet: %s\n", selected_node->planet_Name->Planet_Name);
    printf("Height: %.2f, Velocity: %.2f\n", height, velocity);
} else {
    // 处理异常情况,比如用户输入了无效索引
    printf("Failed to load planet data!\n");
}

额外提醒:确保链表正确初始化

还要注意,在你创建链表节点的时候,必须给每个PlanetNode_t的planet_Name指针分配有效的Planet_t内存并赋值,比如:

// 示例:创建Pluto节点并添加到链表
Planet_t* pluto = calloc(1, sizeof(Planet_t));
strcpy(pluto->Planet_Name, "Pluto");
pluto->Height = 100.0; // 替换成你的实际数据
pluto->Velocity = 50.0;
pluto->Fuel = 1000.0;
pluto->Gravity = 0.62;
pluto->Maximum_Thrust = 200;
pluto->Difficulty = 0.0;

PlanetNode_t* pluto_node = calloc(1, sizeof(PlanetNode_t));
pluto_node->planet_Name = pluto;
pluto_node->next = NULL;

// 添加到链表
SolarSystem->head = pluto_node;
SolarSystem->count = 1;

// 同理添加Moon、Mercury、Mars等节点...

这样每次迭代切换PlanetNum时,调用get_planet_node就能准确拿到对应行星的节点,再提取数据就没问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:14:38