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 が表示されないようです...ただ先に進んでいます。今のところ、それを修正する方法がわかりません。