2016-11-12 101 views
-2

基本上在下面的代碼中,我試圖在列表中插入一些名字和一些年齡並將它們打印出來。但是,我的程序只打印列表的姓氏和年齡。有什麼建議麼?打印列表中的元素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; 

Person *headp = NULL; 
static Person* insert(Person *p, char *name, int age) 
{ 
    p = (Person*)malloc(sizeof(Person)); 
    if (p == NULL) 
    abort(); 
    p->name = name; 
    p->age = age; 
    p->next = headp; 
    return p; 
} 

int main(int argc, char **argv) 
{ 
    Person *people=headp; 
    for (int i = 0; i < 7; i++) 
    { 
    people = insert (people, names[i], ages[i]); 
    } 
    while (people != NULL) 
    { 
    printf ("name: %s, age: %i\n", people->name, people->age); 
    people= people->next; 
    } 
    return 0; 
} 

回答

0

您可能不得不重新分配到headppeople一旦你完成插入,因爲否則people指針仍然指向最後一個人(因爲你在每一次插入推進people指針)。

2

要覆蓋傳遞的變量pmalloc返回的地址(內存泄漏和你失去了先前的頭),更改爲:

static Person *insert(Person *head, char *name, int age) 
{ 
    Person *p = malloc(sizeof(Person)); /* Don't cast malloc */ 

    if (p == NULL) 
    abort(); 
    p->name = name; 
    p->age = age; 
    p->next = head; 
    return p; 
} 
+0

這是工作....但它打印出的元素以相反的順序...即,第一個元素是最後一個... –

+0

然後將'for(int i = 0; i <7; i ++)'改爲'for(int i = 6; i> = 0; i - )' –

+2

@RalucaDamarisLupeş :這是如何令人驚訝?你已經設計了你的'insert'函數,像'prepend'而不是'append'。 –