【发布时间】:2018-05-07 08:38:32
【问题描述】:
我发现了其他类似但不完全相同的问题,如果我弄错了,请留下链接:)
我一直在尝试用 C 实现一个 shell,在解析管道时,我考虑过使用 char** args 的链表。
我的解析函数在返回整个列表时出现问题。我使用 tmp 节点在创建新节点时继续移动,但是当我想返回原始头时,它的下一个是 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;
}
}
如果你能指出我正确的方向或告诉我我做错了什么,那就太好了。
【问题讨论】:
-
第一次来:
tmp = tmp->next,tmp->next从未初始化过。 -
我后来用
tmp=malloc(sizeof(node))malloc'd -
这就是问题所在。您 之后 分配了它。您可能对编程的工作原理有一个严重的误解。
-
而
tmp=tmp->next; tmp=malloc(sizeof(node));没有意义,就像写a = 5; a = 10一样。
标签: c linked-list singly-linked-list