I just started programming in C a few weeks ago and I am getting a segmentation fault in my program.
I believe it is because of those lines:
for (int i =0; i < HOW_MANY; i++)
{
people = people -> next;
if (people -> next == NULL) return people;
} //for
}//else
Here is my C program with comments based on my psedocode
struct person *insert_end (struct person *people, char *name, int age) {
//create a new space for the new person
struct person *pointer = malloc(sizeof(struct person));
// check it succeeded
if(pointer == NULL)
{
printf("The program could not allocate memory ");
exit(-1);
}
// set the data for the new person
strcpy(pointer -> name, name);
pointer -> age = age;
pointer -> next = people;
// if the current list is empty
if (people == NULL)
{
// set the new person's "next" link to point to the current list"
pointer -> next = people;
// return a pointer to the new person
return pointer;
}
else
{
// we need a loop to find the last item in the list
// (the one which as a "next" link of NULL)
for (int i =0; i < HOW_MANY; i++)
{
// set the "next link of this item to point
// to the new person, so that the person
// becomes the last item in the list
// (the next person should have a "next" link of NULL)
people = people -> next;
if (people -> next == NULL)
return people;
} //for
}//else
// return the start of the list
return pointer;
}
Also, let me know in case you need my full C code for the program, since this is only a method
Thank you,
Sarah :)