2014-03-19 124 views
1

我在調試鏈接列表程序時遇到問題。它只是在前幾行後崩潰,我認爲這可能是一個scanf問題,然後再次檢查,但仍然無法運行。它在創建新節點的函數中間崩潰。這裏是函數的代碼和main。鏈接列表C程序錯誤

std* CreateNode() 
{  
    std *newnd; 
    char nm[20]; 
    double g; 
    printf("\nCreating node\n"); 
    printf("\nEnter the student's name:\n"); 
    scanf("%s", &nm); 
    printf ("\nEnter the student's GPA:\n"); 
    scanf("%lf", &g); 
    strcpy((newnd->name), nm); 
    newnd->GPA = g; 
    newnd->next = NULL; 
    return newnd; 
} 

int main() 
{ 
    list_head = (std*) malloc(sizeof(std)); 
    list_tail=(std*) malloc(sizeof(std)); 
    list_tail=(std*) malloc(sizeof(std)); 

    list_head=CreateNode(); 
    A=CreateNode(); 
    B=CreateNode(); 
    C=CreateNode(); 
    PrintList(list_head); 
    InsertBeg(A); 
    InsertEnd(B); 
    InsertMiddle(C); 
    PrintList(list_head); 
    SearchStudent(); 
    DeleteMiddle(); 
    DeleteEnd(); 
    DeleteBeg(); 
    PrintList(list_head); 
    return 0; 
} 

當我運行程序時,它會在我進入gpa後立即停止執行。

任何幫助將非常歡迎我試過了我能想到的一切。 謝謝! :)

回答

2

您聲明

std* newnd; 

但是你您嘗試訪問它的成員以前從未爲它分配內存。

std* newnd = malloc(sizeof *newnd ); 
+0

更好:'std * newnd =(std *)malloc(sizeof(newnd));' – zentrunix

+0

@JoséX。不要施放malloc的結果。 http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – clcto

+0

sizeof是一個運算符而不是函數。不需要父母 –

0
在你的程序

std *newnd; 

是你在哪裏分配內存給它的指針?你使用了變量而沒有分配內存給它

strcpy((newnd->name), nm); 
newnd->GPA = g; 
newnd->next = NULL; 

這會導致程序崩潰。所以在使用變量之前分配內存。