2013-04-23 19 views
1

我想用C來實現鏈表:鏈接列表 - 訪問衝突...在哪裏?

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

typedef struct el{ 
    int number; 
    struct el *next; 
} linkedlist; 

linkedlist* newel(){ 
    linkedlist *newelement = (linkedlist*)malloc(sizeof(linkedlist)); 
    newelement->number = 10; 
    newelement->next=NULL; 
    return newelement; 
} 

void add(linkedlist **head, linkedlist *item){ 
    if(!*head){ 
     *head = item; 
    } 
    else{ 
     item->next = *head; 
     *head = item; 
    } 
} 

void prnt(linkedlist *head){ 
    while(head!=NULL){ 
     printf("%d\n", head->number); 
     head=head->next; 
    } 
} 

int main(){ 

    linkedlist *hd; 
    add(&hd,newel()); 
    add(&hd,newel()); 
    add(&hd,newel()); 
    prnt(hd); 

    system("PAUSE"); 

    return 0; 
} 

,我也得到:

Unhandled exception at 0x010c14e9 in test.exe: 0xC0000005: Access violation reading location 0xcccccccc. 

我試圖調試和問題是在PRNT功能。當頭指向最後一個元素時,它似乎沒有看到NULL ...它只是繼續前進。 我不知道如何解決它現在。

回答

4

在你的主函數,初始化:

linkedlist *hd = NULL; 
2

linkedlist *hd;這可能會導致錯誤。因爲最初它可能有一些garbage價值。所以你必須NULL爲頭linkedlist *hd = NULL;

1

我認爲引起例外的原因是hd是一個未初始化的變量。在您的環境中,它似乎攜帶值0xcccccccc。支票if(!*head)可能從未被評估爲`true