0

So basically in the code below I am trying to create a list which contains some names and ages. I don't receive any errors or warnings but it doesn't print anything. What I am doing wrong?

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

1 Answer 1

1

Assigning to p inside the function does not change people from main, which is why you should find people to still be NULL when you go about printing.

You could return the new value for p from insert and assign that value to people.

Sign up to request clarification or add additional context in comments.

2 Comments

How exactly would I do that? What type should the function insert be?
If it is returning the value in p, it would be the same type as p.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.