2016-02-11 73 views
2

因此,我在一個單獨的函數中創建鏈接列表,並且當我打印出函數中的鏈接列表時,似乎一切正常。然而;當我轉到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); 
+2

'createLL(headOne,currOne,ch,number);'這是行不通的:它不可能改變'headOne',它將永遠是NULL。 –

+0

擴展Martin評論,您需要將指針傳遞給createLL中的指針,以便您可以修改例程中在main中聲明的列表。也就是說,createLL的簽名應該是這樣的:void createLL(struct node ** head,struct node ** curr,char ch,int number) – Harald

+0

另外請注意,在SO上發佈的大約一半的LL問題有這個問題,並且有很多。 –

回答

2

在C函數中按值傳遞所有參數。所以如果你想在函數中改變一個變量,你需要傳遞該變量的地址並在函數中解引用參數。

另外,您沒有爲節點分配適量的空間。你想sizeof(struct node),而不是sizeof(struct node *)

void createLL(struct node **head, struct node **curr, char ch, int number){ 
//lowest digit is the head 
    while (((scanf(" %c",&ch)) >= 0)){ 
     // don't cast the return value of malloc 
     *curr = 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); 
} 
+0

hrmm,現在我正在採集這個 錯誤:請求成員'數據'的東西不是結構或工會 – user3260745

+0

@ user3260745可能是一個錯字。將有問題的代碼發佈爲更新,但保留原始代碼。 – dbush

+0

是啊,我正在嘗試將curr的指針指向數據而不先解析它。我認爲這是一個優先順序錯誤。 – user3260745