我已经编写了一些代码来创建整数的单链表并打印出项目。在打印出列表中的所有项目后,我打印出“head->item”并获得了第一个节点中整数的值。
我很纳闷为什么我可以这样做,因为在print()函数中,我写了“head = head->next”,所以这意味着head被改变了吗?
main()
int n;
int value;
ListNode *head = NULL;
ListNode *temp = NULL;
printf("Enter a value: ");
scanf("%d", &n);
while (n != -1)
{
if (head == NULL)
{
head = malloc(sizeof(ListNode));//create the head first
temp = head;//get temp to have the same value as head, so we do not accidently edit head
}
else
{
temp->next = malloc(sizeof(ListNode));//allocate space for the next node
temp = temp->next;//let temp be the next node
}
temp->item = n;//allocate a value for the node
temp->next = NULL;//specify a NULL value for the next node so as to be able to allocate space
scanf("%d", &n);
}
print(head);
printf("%d\n", head->item);//why can I still get the integer in the first node
while (head != NULL)
{
temp = head;
head = head->next;
free(temp);
}
head = NULL;
return 0;
}
void print(ListNode *head)
{
if (head == NULL)
{
return;
}
while (head != NULL)
{
printf("%i\n", head->item);
head = head->next;
}
}
最佳答案
head
可以看作是对列表的“引用”,但它实际上是一个数字(第一个节点的地址)。
因此,调用以 head
作为参数的函数只需将此“数字”(地址)复制到堆栈,并创建一个新变量(也称为 head
) 以相同的地址发起。
由于函数内的 head
是一个不同的变量,因此更改它不会更改原始 head
。
考虑这种情况:
void func(int x)
{
x=1;
}
...
int x=0;
func(x);
printf("%d",x); //Prints '0'
...
确保您理解为什么在这个简单示例中 x
的值没有改变。的确,指针似乎改变了参数传递的行为,但这并不意味着突然间一切都“通过引用”传递。
记住这条规则:为了修改函数中变量的值,您需要发送一个指向该变量的指针。那么,当您想要将一个指针 更改为一个变量时会发生什么?那么,根据规则,您必须将一个指针传递给指针。
因此,如果您想修改 head
(您可能不想),请像这样重构它:
void print(ListNode **head)
{
if (*head == NULL)
{
return;
}
while (*head != NULL)
{
printf("%i\n", *head->item);
*head = *head->next;
}
}
现在实际的调用是 print(&head)
。
关于c - 打印链表时,为什么原来的头指针没有变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22577711/