I have been having a go at making a linked list. I seem to be able to add entries to the list ok but when I try to traverse the list and print its contents I get repeated data.
#include <stdio.h>
#include <stdlib.h>
struct Entry
{
char *FirstName;
Entry *NextEntry;
};
Entry *AddEntry(Entry *ptrHead, char *FirstName);
void DisplayEntries(Entry *StartOfList);
int main()
{
char TempString[80];
int i;
Entry *ptrHead = NULL;
for (i = 0; i < 3; i++)
{
printf ("Enter name: ");
scanf ("%s", TempString);
ptrHead = AddEntry(ptrHead, TempString);
printf("%s was added to the list at address %p with the next address at %p\n", ptrHead->FirstName, ptrHead, ptrHead->NextEntry);
}
DisplayEntries(ptrHead);
return 0;
}
Entry *AddEntry(Entry *ptrHead, char *FirstName)
{
Entry *NewEntry;
NewEntry = new Entry;
NewEntry->FirstName = FirstName;
if(ptrHead == NULL)
{
//printf("First item\n");
NewEntry->NextEntry = NULL;
}
else
{
//printf("Later item\n");
NewEntry->NextEntry = ptrHead;
//printf("Next entry has the address %p\n", ptrHead);
}
ptrHead = NewEntry;
return ptrHead;
}
void DisplayEntries(Entry *StartOfList)
{
Entry *TempEntry;
int i;
TempEntry = StartOfList;
for(i = 0; i < 3; i++)
{
if (TempEntry == NULL)
{
printf("End of list!\n");
}
else
{
printf("%s is at address= %p\n", TempEntry->FirstName, TempEntry);
TempEntry = TempEntry->NextEntry;
}
}
}
And here is my programs output:
Enter name: A
A was added to the list at address 0x804a008 with the next address at (nil)
Enter name: B
B was added to the list at address 0x804a018 with the next address at 0x804a008
Enter name: C
C was added to the list at address 0x804a028 with the next address at 0x804a018
C is at address= 0x804a028
C is at address= 0x804a018
C is at address= 0x804a008
I notice that the addresses are correct showing it is working through the list, but why is the name always the same?
The problem arises from your use of a charater pointer.
In addEntry() you assign the address of TempString (which was passed from main) to all 3 nodes. The last value stored there was 'C' - so that's what is there.
Use a std::string, or at least a character array to make a copy of what is in TempString for each Entry.
You could stick with the char* if you use it to allocate memory for an array to copy TempStrings contents to.
You will also want to add a deleteList() so you can free the dynamically allocated memory for the 3 Entrys. Your program currently has a memory leak because you have calls to new but no calls to delete.