我面临这个问题,如果我通过一个函数(插入一个节点)传递一个链表(我定义为全局),一旦指针返回到主函数,我总是得到一个 NULL 值。 但是,如果我将节点添加到全局定义中,它工作正常,这也是预期的。有人可以帮我解释一下为什么这段代码不起作用并且 *list 总是指向 NULL
struct node{
int val;
struct node *next;
};
typedef struct node node;
static node *list=NULL;
boolean add_node(node *list, int n, int val)
{
node *temp=NULL;
temp = (node *)malloc(sizeof(node));
temp->val = val;
temp->next = NULL;
if((list==NULL) && (n!=0))
{
printf("link list is NULL and addition at non zero index !");
return (FALSE);
}
if(list==NULL)
{
printf("list is NULL ");
list= temp;
}
else if(n==0)
{
temp-> next = list;
list=temp;
}
else
{
node *temp2;
temp2 = list;
int count =0;
while(count++ != (n-1))
{
temp2 = temp2->next;
if(temp2==NULL)
{
printf("nth index %d is more then the length of link list %d ",n,count);
return (FALSE);
}
}
node *temp3;
temp3 = temp2->next;
temp2-> next = temp;
temp->next = temp3;
}
printf("List after node insertion \n");
print_link_list(list);
return (TRUE);
}
main()
{
c= getchar();
switch(c)
{
case 'I':
{
printf("Insert a index and value \n");
int index,value;
scanf_s("%d",&index);
scanf_s("%d",&value);
if(add_node(list,index,value)==FALSE)
{
printf("Couldn't add the node \n");
}
if(list==NULL)
{
printf("\n After Insert op.,list is NULL, add %x",list);
}
else
{
printf("After Inset op., list is not Null, add %x",list);
}
}
break;
case 'D':
....
}
最佳答案
全局变量list
永远不会被修改,只有参数list
。
您可能希望该参数是指向指针的指针,并通过而不是 分配参数。
关于c - 通过函数传递时指向 NULL 的全局链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19501821/