2014-04-19 72 views
0

我正在努力完成我的編程作業,並且需要一個鏈接列表。基本上我們必須創建一個包含特定功能的程序來管理鏈表。相當標準。我上週試過了,只是無法得到它。我試圖在本週末開始工作,並且在我遇到分段錯誤之前取得了良好的進展。使用鏈接列表和字符數組時分段錯誤

struct STUDENT 
{ 
    char *FirstName; 
    char *LastName; 
    char *PUID; 
    int age; 
    struct STUDENT *next; 
}; 

這是我試圖使用的結構。前三個值是char數組,第四個只是一個數字。在此之後,我嘗試在全局聲明一個起始節點和當前節點。

struct STUDENT *head = NULL; 
struct STUDENT *curr = NULL; 

在此之後,我有我的創建節點功能,它需要用戶輸入並將其放入列表中。

void *createListNode() 
{ 
    char first[MAXNAME]; 
    char last[MAXNAME]; 
    char ID[MAXID]; 
    char *pfirst; 
    char *plast; 
    char *pID; 
    int tage; 
    struct STUDENT *temp = (struct STUDENT *) malloc (sizeof(struct STUDENT)); 

    printf("Enter a first name: "); 
    scanf("%s", first); 
    pfirst = first; 
    printf("entered name: %s\n", pfirst); 

    printf("Enter a last name: "); 
    scanf("%s", last); 
    plast = last; 
    printf("entered name: %s\n", plast); 

    printf("Enter the Purdue ID: "); 
    scanf("%s", ID); 
    pID = ID; 
    printf("ID: %s\n", pID); 

    printf("Enter an age: "); 
    scanf("%d", &tage); 
    printf("age: %d\n", tage); 

    temp->FirstName = strdup(first); 
    printf("first\n"); 
    temp->LastName = strdup(last); 
    printf("last\n"); 
    temp->PUID = strdup(ID); 
    printf("id\n"); 
    temp->age = tage; 
    printf("age\n"); 
    temp->next = NULL; 
    printf("next\n"); 

    if (curr == NULL) 
    { 
     printf("inside if\n"); 

     head->next = temp; //-------SEGMENTATION FAULT--------------------- 

     printf("line 107\n"); 
     head = curr = temp; 
     printf("line 109\n"); 
    } 
    else 
    { 
     curr = temp; 
    } 

} 

背景的什麼,我做了這一點: 我得到分段錯誤,當我試圖在我的陣列分配給我的「溫度」節點,而是通過使用它的malloc我解決了這個問題。使用打印語句,我已將問題跟蹤到指定的行。當我嘗試運行代碼時,出現分段錯誤。我嘗試同樣的malloc代碼上面的「頭」和「CURR」節點,但是這給了我:

[email protected]:~/CNIT315$ gcc lab5.c 
lab5.c:20:64: error: invalid initializer 
struct STUDENT head = (struct STUDENT *) malloc (sizeof(struct STUDENT)); 

這是我認爲這個問題是的,但我一直在尋找和試驗了好幾個小時並沒有得到任何地方。我剛剛意識到這是一個很長的職位。感謝您閱讀並感謝您的正確方向!

回答

0

您將head初始化爲NULL。在分配一個有效的指針之前,您無法取消引用headhead->next = temp;給你一個段錯誤,因爲head是一個空指針。

因此,你需要檢查這部分代碼:

if (curr == NULL) 
    { 
     printf("inside if\n"); 

     head->next = temp; //-------SEGMENTATION FAULT--------------------- 

     printf("line 107\n"); 
     head = curr = temp; 
     printf("line 109\n"); 
    } else 
    { 
     curr = temp; 
    } 

因爲它似乎像你想在列表的末尾插入,我建議是這樣的:

temp->next = NULL; 
if (head == NULL) { 
    curr = head = temp; 
} else { 
    curr->next = temp; 
    curr = temp; 
} 

這使得curr總是指向最後一個節點,並且head總是指向列表的開始。

0

我錯了嗎?還是你設置了head->next = temp;但是從未將head設置爲有效的對象? 您可能已在開始與「空」學生初始化head或者你只需​​要設置head = temp;

0

假定您已經定義了createListNode()功能外head變量,這裏的問題:

內存永遠不會分配給它,因爲您從未撥打過malloc()

+0

@Filipe:你的建議擺脫了分段錯誤。我仍然覺得我需要在我的頭節點上使用malloc()。最後的代碼框顯示了當我試圖在頭節點上使用malloc()時發生了什麼。這是你的意思嗎?如果是這樣,你是否看到我出錯的地方? – user3552361