首页 > 解决方案 > 结构在链表 C 语言中不起作用

问题描述

在下面的代码中,一段代码正在运行,但如果我评论它并运行第二段它不起作用,为什么?

typedef struct {

    float gravity;
    float difficulty;

}planet_t;

typedef struct list {
    struct list * next;
    planet_t planet;
}list_t;

int main()
{

    //this piece works
    list_t * planetList;
    planetList = malloc(sizeof(list_t));
    planetList->planet.gravity=9.8;
    planetList->planet.difficulty = 2;
    planetList->next = NULL;

    //this does not work

    list_t * planetList;
    list_t * temp = planetList;
    temp=malloc(sizeof(list_t));
    temp->planet.gravity=9.8;
    temp->planet.difficulty = 2;
    temp->next = NULL;

    /* let's assume here is the working code which prints all the elements in Linked List */
}

谁能告诉我我在这里遗漏了什么?

标签: cstructlinked-list

解决方案


指针只是指向内存的数字。

考虑这部分代码:

list_t * planetList; 
list_t * temp = planetList;
temp=malloc(sizeof(list_t));

让我们逐行分解代码。

list_t * planetList; 

您刚刚声明了一个指针(数字)并且该未初始化。

list_t * temp = planetList;

您声明了另一个指针(数字),并且该等于 的未初始化值planetList

temp=malloc(sizeof(list_t));

您将value of设置temp为任何malloc()返回值。
保持未planetList初始化。

正如@Jonathan 指出的那样,您的问题可能是planetList从未设置为任何内容,因此您无法使用它。


推荐阅读