-2
在下面的程序中,我尝试将元素插入列表的末尾并将其打印出来。但是,如果(headp-> next == NULL),我得到一个分段错误。我究竟做错了什么 ?有什么建议么?谢谢!在列表的末尾插入一个元素C
#include <stdio.h>
#include <stdlib.h>
/* these arrays are just used to give the parameters to 'insert',
to create the 'people' array
*/
#define HOW_MANY 7
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
typedef struct person
{
char *name;
int age;
struct person *next;
}Person;
static Person* insert_end(Person *headp, char *name, int age)
{
Person *p = malloc(sizeof(Person));
if (p == NULL)
abort();
p->name = name;
p->age = age;
if (headp->next == NULL)
{
headp->next = p;
return p;
}
else
{
Person *current = headp;
while(current->next != NULL)
{
current = current->next;
}
current->next = p;
return p;
}
}
int main(int argc, char **argv)
{
Person *people1 = NULL;
for (int i = 0; i < 7; i++)
{
people1 = insert_end(people1, names[i], ages[i]);
}
while(people1 != NULL)
{
printf ("name: %s, age: %i\n", people1->name, people1->age);
people1 = people1->next;
}
return 0;
}
一个调试器下运行你的代码。 –
在调试器中运行它,你会看到 –
问自己:第一个元素(people1)为空,但接下来它是否有下一个?当标题被分配?(答案:从不),首先确保你的第一个项目被分配,然后继续前进 – LiorA