在下面的代码中,一段代码可以工作,但是如果我评论它并运行第二段代码,它就不起作用,为什么?
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/