我面临着这个问题,如果我通过函数(插入节点)传递链表(我定义为全局),一旦指针返回到主函数,我总是会得到一个 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
。
您可能希望该参数是指向指针的指针,并通过参数而不是参数进行赋值。
尝试更改函数定义以使用指向指针的指针:
boolean add_node(node **list, int n, int val)
您需要这样做,因为您的全局变量list
需要更新。全局是一个指针:一个地址。在add_node
函数中,当您说list = temp
时,您只是在修改本地指针(也称为列表)。当您离开函数时,全局列表保持不变。但是,如果将指针传递给该全局指针(指向指针的指针),则可以修改存储在原始指针中的地址。
举个例子:
int *pGlobal = NULL;
void someThing(int *pInt)
{
int LocalInt = 3;
pInt = &LocalInt; // I can change where this pointer is pointing - it's just a copy
// pGlobal remains unchanged
}
void someThingElse(int **ppInt)
{
// I am now modifying the ADDRESS of a pointer that we have the address of
*ppInt = malloc(sizeof(int));
// pGlobal has been changed to point at my allocated memory
}
void main()
{
// This passes a COPY of the address held in pGlobal
someThing(pGlobal);
// Here we are now passing a pointer (address) TO another pointer.
// The pointer pGlobal does occupy some real space in memory. We are passing a
// COPY of the value of its location so we can modify it.
someThingElse(&pGlobal);
}
此外,为了好的做法,不要将全局命名为与局部变量(列表)或参数相同的名称 - 它会编译,但很容易导致问题/混乱/错误!