I want to create a vector of char* by reading strings from a input text file.
The vector is created properly but when displayed I see that the last element
which is inserted is displayed for all the 'n' number of elements of vector.
What might be the issue?
My task is to read a series of words from an input text file, insert them to a list and display it on screen. For the same I am creating a list of char pointers. While trying to display the list I see that the last word is only displayed repeatedly. It means my list is created properly but while populating there is some issue.
Using std::strings is working fine but I want to know what is going wrong with char*.
When you read the data in from the text file, do you store it somewhere?
If not, that's your problem. char*s are simply pointers to arrays of characters that reside somewhere. If all you do is read from the file, and store that pointer you get back in the array, it's possible that those pointers are all just pointers to the same internal buffer in the file, depending on what you are using to reading from the file.
That would explain all of the elements being the same. If those pointers are just pointers to an internal buffer somewhere, then the pointers will all be the same, to that internal buffer. Then that buffer is getting over-written every time you read another word in, with all the pointers pointing to it, with the last word you read in residing in it when you print out the array's contents.
So, make sure you actually store the data you read in from the file somewhere dedicated. A std::string does this for you, it's probably the way to go.