在C中列出列表末尾的元素

时间:2016-11-12 14:13:27

标签: c

在下面的程序中,我尝试在列表的末尾插入元素并将其打印出来。但是我在if(headp-> next == NULL)处得到了Segmentation故障。我究竟做错了什么 ?有什么建议?谢谢!

   #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;
    }

1 个答案:

答案 0 :(得分:0)

最初当列表为空时,headp等于NULL

因此这些陈述

if (headp->next == NULL)

while(current->next != NULL)

导致未定义的行为。

您也忘了将附加节点的数据成员next初始化为NULL。

该功能可以写得更简单

static int insert_end( Person **headp, char *name, int age ) 
{
    Person *p = malloc( sizeof( Person ) ); 
    int success = p != NULL;

    if ( success )
    {
        p->name = name;
        p->age  = age;
        p->next = NULL;

        wjile ( *headp ) headp = &( *headp )->next; 

        *headp = p;
    }

    return success;
}

该功能可以像

一样调用
size_t i = 0;

while ( i < sizeof( names ) / sizeof( *names ) && 
        insert_end( &people1, names[i], ages[i] ) ) i++