c - 结构体在 C 语言链表中不起作用

标签 c struct linked-list

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

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 */
}

有人可以告诉我我在这里错过了什么吗?

最佳答案

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

考虑这部分代码:

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

您将 temp设置为 malloc() 返回的值。
planetList 保持未初始化状态。

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

关于c - 结构体在 C 语言链表中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50429139/

相关文章:

c - 无法从链表中弹出顶部元素

无缘无故的C段错误

c++ - 在 C++ 中不重载 operator== 的结构成员相等性

python - 排序双向链表 Python

c - 用 C 将结构写入文件

c - 如何 fread() 结构?

java - 实现一个链表栈和队列,不知道自己设置的代码是否足够高效

c - 分段故障

创建一个链表来注册 C 学生

Cygwin 或 Gnuwin32 或 MYSYS?