因此,我在一個單獨的函數中創建鏈接列表,並且當我打印出函數中的鏈接列表時,似乎一切正常。然而;當我轉到main並嘗試使用printf訪問鏈接列表時,我得到了一個分段錯誤,我很困惑,爲什麼。創建鏈接列表,不傳回主
void createLL(struct node* head, struct node* curr, char ch, int number){
//lowest digit is the head
while (((scanf(" %c",&ch)) >= 0)){
curr = (struct node*)malloc(sizeof(struct node*)); //allocate space
number = ch - '0' ; //convert char to number
curr->data = number;
curr->next = head;
head = curr;
}
curr = head;
//troubleshoot
while(curr){
printf("%d\n",curr->data);
curr = curr->next;
}
curr = head;
printf("%d\n",curr->data);
}
int main(){
//initials
int i, number;
char ch;
//node pointers
struct node* headOne = NULL;
struct node* currOne = NULL;
struct node* headTwo = NULL;
struct node* currTwo = NULL;
//create linked list
createLL(headOne,currOne, ch, number);
printf("%d\n",currOne->data);
createLL(headTwo,currTwo, ch, number);
printf("%d\n",currTwo->data);
'createLL(headOne,currOne,ch,number);'這是行不通的:它不可能改變'headOne',它將永遠是NULL。 –
擴展Martin評論,您需要將指針傳遞給createLL中的指針,以便您可以修改例程中在main中聲明的列表。也就是說,createLL的簽名應該是這樣的:void createLL(struct node ** head,struct node ** curr,char ch,int number) – Harald
另外請注意,在SO上發佈的大約一半的LL問題有這個問題,並且有很多。 –