2016-11-12 109 views
-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; 
    } 
+1

一个调试器下运行你的代码。 –

+1

在调试器中运行它,你会看到 –

+1

问自己:第一个元素(people1)为空,但接下来它是否有下一个?当标题被分配?(答案:从不),首先确保你的第一个项目被分配,然后继续前进 – LiorA

回答

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++