在C中打印列表的元素

时间:2016-11-12 12:38:28

标签: 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;
}

2 个答案:

答案 0 :(得分:2)

您正在使用p返回的地址覆盖传递的变量malloc(内存泄漏并且您松开前一个头),更改为:

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

答案 1 :(得分:0)

插入完成后,您可能需要将headp重新分配给people,否则people指针仍会指向最后一个人(因为您提前people每个插入中的指针)。