我已經在C中編寫了自己的列表,但在向其中添加第二個對象時,我拋出了異常:寫入訪問衝突。它發生在addToList()函數中(我評論過該行)。你能告訴我爲什麼我得到一個錯誤。我一直在初始化主要方法頭:將結構添加到列表中時出現Nullptr錯誤
void main()
{
struct List *head = malloc(sizeof(head));
head->next = NULL;
head->person = NULL;
//head = NULL;
addToList(head,"Abdul","Marin","21312321321");
addToList(head, "Karmowski", "Byk", "24214541");
displayList(head);
getchar();
return 0;
}
List.h文件:
struct List
{
struct Person *person;
struct List *next;
};
List.c文件:
void addToList(struct List * head, char *name, char *surname, char *id)
{
struct List *tmp = head;
struct Osoba *newPerson= malloc(sizeof *newPerson);
newPerson->name = name;
newPerson->surname = surname;
newPerson->id = id;
if (tmp->person==NULL)
{
head->person = newPerson;
}
else if (tmp->next==NULL)
{
head->next->person = newPerson; // HERE OCCURES ERROR
}
else
{
while (tmp->next!=NULL)
{
tmp = tmp->next;
}
tmp->next->person = newPerson;
}
}
您確定'tmp = head'和'tmp-> next == NULL',那麼您爲什麼期望能夠訪問'head-> next-> person'? – UnholySheep