2016-08-21 84 views
0

我是新來的鏈接列表,但我試圖創建一個鏈接列表和3個元素,並且編寫一個函數來計算所述鏈接列表中的元素數量。 我不斷收到分段錯誤,但我找不出原因。 任何幫助將是最受歡迎的。當鏈接列表中的元素計數時出現分段錯誤

#include <stdio.h> 
#include <stdlib.h> 

typedef struct node {  // create a struct to build a 
    int    data;  // linked list 
    struct node* next; 
}; 

struct node* BuildOneTwoThree() { 
    struct node* head = NULL;   // pointers 
    struct node* second = NULL;  // for 
    struct node* third = NULL;   // linked list 

    // allocate memory on the heap for the 3 nodes 
    head = malloc(sizeof(struct node)); 
    second = malloc(sizeof(struct node)); 
    third = malloc(sizeof(struct node)); 

    head->data = 1;  // set up 1st node 
    head->next = second; 

    second->data = 2;  // set up 2nd node 
    second->next = third; 

    third->data = 3;  // set up 3rd node 
    third->next = NULL; 

    return head; 

} 

void main(){ 
    int num = Length(BuildOneTwoThree); 
    printf("Number of nodes:%d\n", num); 

} 

int Length(struct node* head) { 
    struct node* current = head;  
    int count = 0; 

    while(current != NULL) { 
     count++; 
     current = current->next;  
    } 
    return count; 
} 
+2

在調試器中運行它並查看它發生故障的位置。 –

回答

3

int num = Length(BuildOneTwoThree); 

必須

int num = Length(BuildOneTwoThree()); 
           ^^^ Missing the function call. 

不這樣做,你是justing函數指針Length

您可以在使用它們之前通過提供函數聲明來避免此類錯誤。

struct node* BuildOneTwoThree(); 
int Length(struct node* head); 

隨着在文件的頂部聲明的功能,我從GCC得到以下信息:

soc.c: In function ‘main’: 
soc.c:36:22: warning: passing argument 1 of ‘Length’ from incompatible pointer type [-Wincompatible-pointer-types] 
    int num = Length(BuildOneTwoThree); 
        ^
soc.c:10:5: note: expected ‘struct node *’ but argument is of type ‘struct node * (*)()’ 
int Length(struct node* head); 

typedef struct node { 
    int    data; 
    struct node* next; 
}; 

是不對的。這會在空聲明警告中產生無用的存儲類說明符。需要進行任何

struct node { 
    int    data; 
    struct node* next; 
}; 

struct node { 
    int    data; 
    struct node* next; 
} node; 

而且,main需要返回類型爲int,不void

+0

當我在調試器中運行它時,那是導致seg故障的線路。 我也收到一個警告,我不明白: 警告:無效的存儲類說明符在空聲明[默認情況下啓用] }; ^ –

+0

所以看起來編譯器給出的警告應該是如果我定義了一些東西,但從不聲明它。但是我確實聲明瞭3個我之前定義的節點。 因此,這讓我覺得我還沒有宣佈任何這樣的節點? :/ –

2

您需要更改「主」

int num = Length(BuildOneTwoThree); 

int num = Length(BuildOneTwoThree()); 

該行目前你的編譯器應該拋出一個錯誤,當您編譯此文件作爲「長度」的功能是期待一個'結構節點*',但你傳遞給它一個函數指針。

+0

編譯器看起來很好用:/ –