在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: %in", people->name, people->age);
    people = people->next;
  }
  return 0;
}

在函数内部分配给p不会改变people从main,这就是为什么你应该发现people仍然是NULL当你去打印。

您可以从insert返回p的新值,并将该值赋给people

相关内容

  • 没有找到相关文章

最新更新