为何C语言链表AddatBeginning函数中指针p未被temp赋值更新?
链表头插函数未生效的原因分析
在DevC++中运行以下代码后,未得到预期输出100, 1, 2, 3,实际输出为1,2,3。调试发现AddatBeginning函数中的语句p=temp;未生效,p并未指向temp所指向的地址,请问这是为什么?
问题代码
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *link; }; int main(int argc, char *argv[]) { struct node *p; p = NULL; Append(&p , 1); // Append adds a node to the end of linked list Append(&p , 2); Append(&p , 3); AddatBeginning (p, 100); Display(p); // Displays Elements of Linked List return 0; } // The function AddatBeginning adds a node at the beginning of linked list 'p' void AddatBeginning (struct node *p, int num) { struct node *f, *temp = NULL; f = p; temp = (struct node *)malloc (sizeof(struct node)); temp->data = num; temp->link = f; p=temp; }
原因分析
核心问题在于C语言的参数传递是值传递:
- 调用
AddatBeginning(p, 100)时,传递给函数的是main函数中p指针的副本,而非指针本身。 - 在
AddatBeginning内部修改的只是这个副本的指向(p=temp),完全不会影响main里原本的p指针。这和普通变量的值传递逻辑一致:修改参数副本无法改变原变量。
你可以对比Append函数的调用方式Append(&p, 1)——它传递的是p的地址,所以能直接修改原指针的指向,这也是Append能正常工作的原因。
解决方案
把AddatBeginning的参数改为指针的指针(二级指针),通过地址直接修改原指针:
// 修改后的头插函数 void AddatBeginning(struct node **p, int num) { struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->data = num; temp->link = *p; // 新节点指向原来的链表头 *p = temp; // 修改原指针的指向,让它指向新节点 } // 调用时传入p的地址 AddatBeginning(&p, 100);
修改后,函数就能真正改变main中p的指向,头插的新节点会被Display函数遍历到,输出预期的100, 1, 2, 3。
内容的提问来源于stack exchange,提问作者AVINASH BHARTI
相关产品推荐
相关产品推荐

