2014-03-19 44 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; 

这会导致程序崩溃。所以在使用变量之前分配内存。