c - 你能指出这个菜鸟 C 代码中尝试创建链表的错误吗
问题描述
这是我第一次尝试创建一个linkedList。代码肯定不合适,但我想做的只是能够创建一个列表并用一个节点初始化它。下面的代码在语法上是正确的,但它不起作用。可以指出错误。
#include <stdio.h>
#define SIZE 5
struct node
{ int item;
struct node *link;
};
struct linkedlist
{
struct node *head;
int count;
};
void init(struct linkedlist *p , int key)
{
struct node *newnode;
newnode = (struct node*)malloc(sizeof(struct node));
newnode->link = NULL;
newnode->item = key;
p->head = newnode;
p->count = 1;
}
void main()
{ struct linkedlist *s;
init(s , 2);
printf("%d", s->count);
}
解决方案
s
在函数取消引用之前,您必须分配一个结构并将其指针分配给init
它。
int main(void)
此外,您应该在托管环境中使用 standard而不是void main()
,这在 C89 中是非法的,并且在 C99 或更高版本中是实现定义的,除非您有特殊原因使用非标准签名。
另一个注意事项是malloc()
家庭的铸造结果被认为是一种不好的做法。
int main(void)
{ struct linkedlist *s = malloc(sizeof(*s)); /* allocate the structure */
if (s == NULL) return 1; /* check if allocation succeeded */
init(s , 2);
printf("%d", s->count);
}
免责声明:我没有释放s
它,因为它只分配一次并且执行很快就会结束。该节点也没有被释放。现代操作系统不需要在程序结束时释放。(c - 当你在 malloc 之后不释放时,真正发生了什么? - 堆栈溢出)你可能想要添加释放来满足 Valgrind 等内存检查器。
推荐阅读
- java - 将具有不同原始参数类型的计算方法联合起来的接口
- java - 错误:无法从 Selenium 中的 NUMERIC 单元格获取 STRING 值
- python - pyinstaller制作的程序运行失败
- flutter - 在 Flutter 中将数据从一个小部件列表添加到另一个列表
- unity3d - Gitlab-Runner Shell 自动删除文件
- ios - SwiftUI - 此代码是否实例化了一个新的场景对象?
- javascript - 即使我的代码是正确的,为什么当我尝试 npm start 时我的 electron.js 应用程序不会打开?
- python - Python-Bitcoinlib - FileNotFoundError:找不到模块'libeay32'
- c - 拆分C链表而不复制
- python - Linux中Python子进程之间管道的困难