我試圖做一個函數,將一個節點添加到列表的開頭,然後更改變量「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'的情況是正確的,但是不是指向一個變量的指針,而不是保存變量本身?我假定傳遞一個指針變量,改變指針也會有效地改變原始變量。 –