I'm trying to make this code work.The program compiles but I get this error:"Bus error: 10" after I select option 1. It's a linked list containing type Person structs.
#include <iostream>
int count=0;
struct Person
{
std::string name;
int age;
int id;
Person *next;
};
void PrintPerson(Person *person)
{
std::cout << person->name << " is " << person->age << " years old.\n";
}
struct List
{
//First person in the list, null if list is empty
Person *head;
//Current person in the list, where a null pointer inicate a past-the-end position
Person *current;
//Previous element, null if current is first
Person *previous;
};
void ListNext(List *list)
{
//Moves the current position in the list one element forward
//or to null if it exceeds the list
if (list->current != nullptr)
{
list->previous = list->current;
list->current = list->current->next;
}
}
void ListHead(List *list)
{
//Move the current position to the first element on the list
list->previous = nullptr;
list->current = list->head;
}
Person *ListGet(List *list)
{
return list->current;
}
//Set the current position to the person with the given name. If no person
////exists with that name, then current position is set to past-the-end.
void ListFind(List *list, int id1)
{
ListHead(list);
while (list->current != nullptr && list->current->id != id1)
ListNext(list);
}
void ListInsert(List *list, Person *person)
{
person->next = list->current;
void AddPerson(List *list)
{
Person *person1;
person1->id=count+1;
std::cout<< "Type the person's name: ";
std::cin>> person1->name;
std::cout<< "Enter the person's age: ";
std::cin>> person1->age;
count++;
ListInsert(list,person1);
std::cout<<"Person id"<<person1->id;
PrintPerson(ListGet(list));
}
This code declares a pointer, person1. It is uninitialized, thus can point to pretty much anywhere. It's non-deterministic.
The assignments, like person1->id=count+1;, then overrite areas of memory that person1 is pointing to.
I expect you forgot to allocate a new person as in:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void AddPerson(List *list)
{
Person *person1 = new Person;
person1->next = nullptr;
person1->id=count+1;
std::cout<< "Type the person's name: ";
std::cin>> person1->name;
std::cout<< "Enter the person's age: ";
std::cin>> person1->age;
count++;
ListInsert(list,person1);
std::cout<<"Person id"<<person1->id;
PrintPerson(ListGet(list));
}
Also, in ListInsert, why should person be inserted in the current position? Shouldn't it be inserted relative to head? I would expect current and previous to be concerned with traversing the linked list and shouldn't be used as an insertion point.