我有一個關於通過函數傳遞C中鏈接列表的頭部的問題。所以代碼如下所示:傳遞一個鏈接列表頭通過函數作爲地址在C
#include <stdio.h>
//Defining a structure of the node
struct node {
int data;
struct node* next;
};
void insert (struct node* rec, int x) {
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data = x;
temp->next = NULL;
rec = temp; // head and rec is now pointing to the same node
}
void print(struct node* rec){
printf("%d", rec->data); //error occurs here
puts("");
}
main(){
struct node *head = NULL; //head is currently pointing to NULL
insert (head, 5); //Passing the head pointer and integer 5 to insert()
print(head);
}
因此,如您所見,當我嘗試打印rec->數據時發生錯誤。爲什麼發生錯誤?因爲指針rec和head都指向堆中的同一個節點,所以應該沒有問題?
謝謝。
您需要通過'struct node **'來插入,就像'insert(&head ...'。否則頭不會改變,因爲函數只接收它的值的副本。 – sje397
您可以將列表的頭部通過重新定義'insert'函數的參數 –
並且你可能想'temp-> next = * rec'(假設你傳遞了一個雙指針),否則你將失去列表的其餘部分。 – sje397