首页 > 解决方案 > 你能指出这个菜鸟 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);


}

标签: cpointerslinked-listsingly-linked-list

解决方案


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 等内存检查器。


推荐阅读