我已经在C中编写了自己的列表,但是在向它添加第二个对象时,我已经抛出了异常:写入访问冲突。它出现在addToList()函数中(我已经注释了该行)。你能告诉我为什么我会收到错误吗?我已在主要方法中初始化了头部:
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;
}
}
答案 0 :(得分:1)
**/*function definition for add data in list */
struct list * AddList ( struct list *head, char *name, char *surname, int id )
{
struct person *new_person = NULL ;
struct list *newlist = NULL ;
struct list *tmp = head ;
/* memory allocation for new person */
new_person = ( struct person * ) malloc ( sizeof ( struct person )) ;
if ( NULL == new_person ) {
perror ( "new node malloc failed : \n" ) ;
return NULL ;
}
/* Assign value */
strcpy( new_person->name , name ) ;
strcpy( new_person->surname , surname ) ;
new_person->id = id ;
/* Assign data for head node */
if ( NULL == head->person ) {
head->person = new_person ;
return head ;
} else if ( NULL == head->next ) { /* 2nd Node */
newlist = ( struct list * ) malloc ( sizeof( struct list ) );
newlist->person = new_person;
newlist->next = NULL ;
head->next = newlist ;
return head->next ;
} else { /* New list */
while ( tmp->next ) {
tmp = tmp->next ;
}
/* memory allocation for new list */
newlist = ( struct list * ) malloc ( sizeof( struct list ) );
newlist->person = new_person;
newlist->next = NULL ;
tmp->next = newlist ;
return head->next ;
}
return NULL ;
}
答案 1 :(得分:0)
这是一个问题
struct List *tmp = head;
struct Osoba *newPerson= malloc(sizeof *newPerson);
newPerson->name = name;
newPerson->surname = surname;
newPerson->id = id;
if (tmp->person==NULL)
您无法为newPerson->名称指定名称,并且希望它超出函数范围。
您需要为名称和姓氏分配空间,然后将字符串复制到那里
e.g。
newPerson->name = strdup(name); // malloc/strcpy
答案 2 :(得分:0)
else if (tmp->next==NULL)
{
head->next = malloc(sizeof(struct List));
head->next->person = newPerson;
head->next->next = NULL;
}
和最后一个其他区块相同。
虽然实际上中间块是不必要的;如果tmp->next==NULL
那么while循环将在第一次跳转,因此您不需要将其视为单独的案例。
你的初始malloc看起来也错了:
struct List *head = malloc(sizeof(head));
头是一个指针。你一直在使用sizeof(* head),但我不喜欢它;更好(sizeof(struct Person))
( type 指示sizeof,而不是实例)。
答案 3 :(得分:0)
在访问之前,您忘记将内存分配给head -> next
。
添加
head->next = malloc(sizeof struct List);
就在
之前 head->next->person = newPerson; // HERE OCCURES ERROR