-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