我试图做一个函数,将一个节点添加到列表的开头,然后更改变量“head”(保存列表的前一个开头)以包含新节点。为什么我的链接列表的头部不变?
void addToStart(node * n, node * first){
printf("[Before adding] Node: %d, First: %d\n",&(*n),&(*first));
n->next = first;
first = n;
printf("[After adding] Node: %d, First: %d\n",&(*n),&(*first));
}
int main(){
node * head = createNode(0);
printf("This is the location of head: %d\n",&(*head));
node * fred = createNode(2);
addToStart(fred,head);
traverse(head); //Displays the list starting from the given node
return 0;
}
这是输出:
This is the location of head: 10113040
[Before adding] Node: 10113072, First: 10113040
[After adding] Node: 10113072, First: 10113072
(0)[10113040]->NULL
的问题是,我所期望的功能改变什么head
在指着,但实际上一切都没有改变。
'first = n'在'addToStart'中改变函数参数'first',但不是'main'中的'head'。 'first'是'head'的副本,因为C是按值传递的,只有副本被改变。 –
这与'void f(int n){n = 0; }'不能用于将整数设置为零。和C中的所有东西一样,试着首先了解'int'的情况,然后推广到其他类型。 –
你对'int'的情况是正确的,但是不是指向一个变量的指针,而不是保存变量本身?我假定传递一个指针变量,改变指针也会有效地改变原始变量。 –