2016-11-11 119 views
0

因此,基本上在下面的代碼中,我試圖創建一個包含一些名稱和年齡的列表。我沒有收到任何錯誤或警告,但它不會打印任何內容。我做錯了什麼?插入和打印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 void insert(Person *p, char *name, int age) 
{ 
    Person *headp = NULL; 
    p = (Person*)malloc(sizeof(Person)); 
    if (p == NULL) 
    abort(); 
    p->name = name; 
    p->age = age; 
    p->next = headp; 
    headp = p; 
} 

int main(int argc, char **argv) 
{ 

    Person *people=NULL; 
    for (int i = 0; i < 7; i++) 
    { 
    insert (people, names[i], ages[i]); 
    } 

    while (people != NULL) 
    { 
    printf ("name: %s, age: %i\n", people->name, people->age); 
    people = people->next; 
    } 
    return 0; 
} 

回答

1

分配到p裏面的函數不從主變people,這就是爲什麼你應該找到people仍然是NULL,當你去打印。

您可以從insert返回p的新值,並將該值分配給people

+0

我到底該怎麼做?功能插件應該是什麼類型? –

+0

如果它返回'p'中的值,它將與'p'類型相同。 –