This program is supposed to create a struct array containing the name and age values from the hard coded name and age arrays at the start of the code. I've been explicity asked to declare the array in the main function and then allocate memory to it within the insert function. The program compiles fine and the output i'm supposed to get is:
Name: Simon
Age: 22
Name: Suzie
Age: 24
Name: Alfred
Age: 106
Name: Chip
Age: 6
etc. etc.
However the output I get is something like this:
Name: Simon
Age: 22
Name: (null)
Age: 33
Name: Suzie
Age: 24
Name: (null)
Age: 33
Name: Suzie
Age: 24
..... segmentation fault.
Some of the names appear twice, some of the names are null, and there is a segmentation fault at the end of the output. Any help would be greatly appreciated. many thanks.
#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};
/* declare your struct for a person here */
struct person {
char *name;
int age;
};
static void insert(struct person **arr, char *name, int age)
{
//initialise nextfreeplace
static int nextfreeplace = 0;
//allocate memory
arr[nextfreeplace] = malloc (sizeof(struct person));
/* put name and age into the next free place in the array parameter here */
arr[nextfreeplace]->name = name;
arr[nextfreeplace]->age = age;
/* modify nextfreeplace here */
nextfreeplace++;
}
int main(int argc, char **argv)
{
/* declare the people array here */
struct person *people;
for (int i = 0; i < HOW_MANY; i++)
{
insert (&people, names[i], ages[i]);
}
/* print the people array here*/
for (int i = 0; i < HOW_MANY; i++)
{
printf("Name: %s \t Age: %i \n", people[i].name, people[i].age);
}
return 0;
}