February 3rd, 2003, 03:40 AM
Pointers to Strinks in Linked List (Please Help)
Basically I have a !doubly linked list, which uses structs. It reads in data from the file and stores it in the list. It all works perfectly when I use numbers or characters. But my problem is when I read in strings... I have to use C.
The code still runs fine, but at the end the last read in word overwrites all the ones stored before it. The pointers seem to be connected and thus all values in the set of pointers are changed every time. I dont know how to get around it. I know there must be a trick, and I have tried for two days but without any success.
Hope there is someone outthere who can help!
Thanks so much in advance!
char chars; // Stores the read in word from the file
struct Word * nextPtr;
struct Word * prevPtr;
Word *lastPtr; // The previous struct
Word *mainPtr; // The main struct into which a value is being entered
Word *header; // Header
header = new Word;
lastPtr = header;
if ((filePtr = fopen ("text.txt", "r")) == NULL)
printf ("Error, FILE could not be found!");
//Creating a new Nodes of type Struct for Input Data
mainPtr = new Word;
fscanf (filePtr, "%s", chars); // Read in the word
mainPtr->x=chars; // Here is the problem i think... Once fscanf reads in the word all the previous strings in the previous structs are changed to this one...
lastPtr = mainPtr; // Make the last pointer equal to the main one
mainPtr = header->nextPtr; // Main pointer is set to heather, beggining pointer value
// Testing Data
while (mainPtr->nextPtr != NULL)
printf("Data : %d\n", mainPtr->x); // Prints out the pointer string value (thats the problem)
mainPtr = mainPtr->nextPtr;
printf(">Ptr : %d >\n", mainPtr); // Prints out the pointer value of pointer to the struct
>>>In the testing stage above, I get different pointer address values for the second printout but the first printout for data (x's values) returns same value for all ocurances. That is my problem!
February 3rd, 2003, 03:12 PM
You were spot on; that's the statement with the problem. The thing is that with that statement, you're telling each element of the list to point to the same location, chars. But chars can only hold one string, obviously. What you need to do, is duplicate the string in chars to a new location, and let all the x attributes point to those locations.
Oh, and since you said you had to do it all in C, try getting rid of all the occurrences of new, and replace them with the appropriate calls to malloc(). new is C++, not C.
"A poor programmer is he who blames his tools."
February 4th, 2003, 05:15 AM
One thing you should try to avoid is the use of feof() as a loop condition.
Instead of having this :
Use the fscanf() call as the loop condition, like this :
while ( fscanf (filePtr, "%s", chars) != EOF )