c - 结构在链表 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 */
}
谁能告诉我我在这里遗漏了什么?
解决方案
指针只是指向内存的数字。
考虑这部分代码:
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
从未设置为任何内容,因此您无法使用它。
推荐阅读
- spring - Spring集成http在获取请求中禁用多部分
- python - 我在使用 flask_bootstrap4 时遇到了困难
- oracle - 找出计划的 oracle 作业停止运行的原因
- sas - 列出图书馆中的所有目录
- jenkins - org.tmatesoft.svn.core.SVNException: svn/rbESB/!svn/vcc/default) 检出失败
- spring-data-jpa - Weblogic 10.3.3 :: java.lang.NoSuchMethodError: javax.persistence.spi.PersistenceUnitInfo.getSharedCacheMode()
- node.js - 使用 Node.js 从 SFTP 服务器获取最新文件
- python - 通过请求调用 API 时处理 CAPTCHA
- mongodb - 将对象数组转换为数组数组
- laravel-5 - Eloquent 和 Laravel 中的多个 Where 子句