2016-11-12 107 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++