我发现了其他类似但不完全相同的问题,如果我错了,请留下链接:)
我一直在尝试用 C 实现一个 shell,在使用管道进行解析时,我考虑使用 char** args
的链接列表。
我的解析函数在返回整个列表时出现问题。我使用 tmp 节点在创建新节点时保持移动,但是当我想返回原始头时,它的 next 为 NULL,我认为指向我头的指针 tmp 应该只是一个指针,必须进行更改在我的头上。
这是仅包含问题的简化代码。
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node* next;
} node ;
node* foo()
{
node* head=malloc(sizeof(node));
node* tmp=head;
int i=0;
for(i=0;i<5;i++)
{
tmp=tmp->next;
tmp=malloc(sizeof(node));
tmp->data=i;
}
return head;
}
int main()
{
node* list=foo();
while(list)
{
printf("this is your %d\n",list->data);
list=list->next;
}
}
如果您能指出我正确的方向或告诉我我做错了什么,那就太好了。
最佳答案
node* head=malloc(sizeof(node));
node* tmp=head;
int i=0;
for(i=0;i<5;i++)
{
tmp=tmp->next;
tmp=malloc(sizeof(node));
tmp->data=i;
}
return head;
这里你已经创建了head并给了空间,但你从未初始化过它并在初始化之前返回它
关于C - 创建链表的函数仅返回第一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47454491/