we've to code a function that will get the salary of an employee from a linked list based on a parameter of 'name' matching to an employee's name who is in the list...been having some trouble with this, some help would be much appreciated. (i keep getting an unhandled exception error).
ListOfEmployees empList;
empList.insertEmployee("matthew", 5000);//different function works ok
empList.insertEmployee("brian", 10000);//different function works ok
empList.displayEmployeeList();//different function works ok
empList.getSalary("matthew");
empList.getSalary("brian");
system("pause");
return 0;
I'm still looking at it but I think this part of the code looks a bit dodgy?
head = head->next;
I think you'll lose the original head node after the method ends? since the local variable leadPtr pointing to the original head node will go out of scope. So your list will be losing elements one by one.
here's the error i'm getting by the way:
Unhandled exception at 0x009e2b76 in Lab 8.exe: 0xC0000005: Access violation reading location 0xcdcdcde1.
basically i want to:
make sure the head isn't NULL.
if the head contains the name passed in, display that person's salary.
if not, traverse the list until what's passed in matches a name in the list, and then display thats person's salary.
if it doesn't, notify the user that the name doesn't exist.
am i looking at the logic in the right way?
when you say losing elements do you mean they will be actually be deleted from the list? i thought what i was doing was just a way to traverse across the list one node at a time?
if(head->name == empName) // check if the name is the same
{
// head pointer now points to the next node
// but since the head pointer is overwritten there's
// no way to access the original head node. Memory Leak?
head = head->next;
// print out the salary, the head pointer points to the next node though
// and not the original head node. So it's not the salary
// of the node you were looking for, it's the salary of the next node.
cout << "Employee " << empName << " has salaray of: " << head->salary << endl;
}
well so everytime the matching employee name is actually in the head node, you end up losing that node since you lose any way to get to them. They're not getting deleted though they still exist in memory, you just have no way to access them anymore. And your list will always traverse from the new head node in the pointer instead. If that makes any sense.
That's probably not the only problem though since like you said it crashes without printing anything? Usually a program crash would mean you're trying to access a bad pointer.