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 関数にあります。head が最後の要素を指しているときに NULL が表示されないようです...ただ先に進んでいます。今のところ、それを修正する方法がわかりません。

4

3 に答える 3

4

メイン関数で、次を初期化します。

linkedlist *hd = NULL;
于 2013-04-23T05:59:38.933 に答える
2

linkedlist *hd;これにより、エラーが発生する可能性があります。garbage最初は何らかの価値があるかもしれないからです。だからあなたは頭にNULLする必要がありますlinkedlist *hd = NULL;

于 2013-04-23T06:02:02.163 に答える
1

hd例外の原因は、初期化されていない変数だと思います。あなたの環境では、値を運んでいるようです0xcccccccc。チェックif(!*head)はおそらく決して評価されませんでした`true

于 2013-04-23T06:04:29.513 に答える