在下面的程序中,我嘗試按升序排序人員列表。然而,我得到了一個分段錯誤,我不知道如何改變程序以獲得預期的結果。有什麼建議麼?鏈接列表排序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 int compare_people(Person *p1, Person *p2)
{
return strcmp(p1->name, p2->name);
}
static Person* insert_sorted(Person *headp, char *name, int age)
{
Person *p = malloc(sizeof(Person));
if (p == NULL)
abort();
p->name = name;
p->age = age;
if (headp == NULL)
{
headp = p;
return p;
}
else
{
Person *current = headp;
Person *temp =NULL;
while(current != NULL && compare_people(current, p) < 0)
{
temp = current;
if(compare_people(current,p) > 0)
break;
current = current->next;
}
p->next = current;
temp->next = p;
return headp;
}
}
int main(int argc, char **argv)
{
Person *people2 = NULL;
for (int i = 0; i < 7; i++)
{
people2 = insert_sorted(people2, names[i], ages[i]);
//printf ("name: %s, age: %i\n", people2->name, people2->age);
}
while(people2 != NULL)
{
printf ("name: %s, age: %i\n", people2->name, people2->age);
people2 = people2->next;
}
return 0;
}
當你的調試器會告訴你沒有設置'next'指向任何地方,但你使用它。 –
您將得到的最佳建議是學會使用調試器並學習學習[如何調試小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs /)。從長遠來看,運行到Stackoverflow這樣的基本調試問題對你來說是非生產性的。 – kaylum