以下功能有什么问题吗?不知何故,他们正在创建一个段错误。
struct processNode* create_node()
{
struct processNode* newNode = (struct processNode*)malloc(sizeof(struct processNode));
newNode->next = NULL;
return newNode;
}
struct processNode* append_node(struct processNode* list,struct processNode* newNode )
{
struct processNode* tracker= NULL;
tracker = list;
if(tracker == NULL)
{
tracker = newNode;
}
else
{
while(tracker->next != NULL)
{
tracker =tracker->next;
}
tracker->next = newNode;
tracker = tracker->next;
}
tracker->next=NULL;
tracker = list;
return tracker;
}
我在C中创建一个shell,需要创建一个链接列表来解析用户的命令行。在第二个函数中,我打算返回一个带有新附加指针的新列表;
答案 0 :(得分:1)
我想函数应该返回一个指向列表头部的指针。
假设在list
为NULL
所以这很好:
if(tracker == NULL)
{
tracker = newNode;
}
但是这里
tracker = list; <---- Not good....
return tracker;
您覆盖跟踪器并返回NULL
您可以尝试:
struct processNode* append_node(struct processNode* list,struct processNode* newNode )
{
struct processNode* tracker= NULL;
tracker = list;
if(tracker == NULL)
{
tracker = newNode;
return tracker; // Notice
}
while(tracker->next != NULL)
{
tracker =tracker->next;
}
tracker->next = newNode;
return list;
}
答案 1 :(得分:0)
以下情况会在tracker->next=NULL;
行
tracker != NULL && newNode == NULL
tracker == NULL
....
tracker = tracker->next;
}
//THE FOLLOWING LINE WILL CAUSE PROBLEM
tracker->next=NULL;
tracker = list;
return tracker;
....
}
你可以这样做:
struct processNode* append_node(struct processNode* list,struct processNode* newNode )
{
struct processNode* tracker= NULL;
tracker = list;
if(!newNode){
//Do nothing
}
else if(tracker == NULL)
{
tracker = newNode;
}
else
{
while(tracker->next != NULL)
{
tracker = tracker->next;
}
tracker->next = newNode;
tracker = tracker->next;
}
return tracker;
}