vectorchar* or vectorchar[40]

Started by
2 comments, last by Zahlman 18 years, 8 months ago
hey ok i am tring to keep a vector of char[40]....... i am reading in a string as char[40] and tring to push it in to the vector


std::vector<char*> myLevels;	
char levelFileName[40];
inFile >> levelFileName;
myLevels.push_back(new char[40]);
myLevels.at(level) = levelFileName;


I have tried many different things but .. inknow the the infile gets the data.. but i cant seem to get this to work..
Advertisement
ok, strcpy seems like what you need to do. Right now, you're just getting massive memory leeks by assigning a new value to the stored pointer in the vector.

That is to say: you're copying a POINTER not the DATA. Change it to this and it should work:
std::vector<char*> myLevels;char levelFileName[40];inFile >> levelFileName;myLevels.push_back(new char[40]);strcpy (myLevels.at(level), levelFileName);


of course, you REALLY should be using std::string... it's obvious you're using c++ with std::vector, why make life hard on yourself?

std::vector<std::string> myLevels;std::string levelFileName;inFile >> levelFileName;myLevels.push_back(std::string);myLevels.at(level) = levelFileName;


EDIT: what the heck is level?

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

... oh thanks for that ..your a life saver...seriously..

any ways level was my variable in the for loop
for(int level = 0; level < NumberofLevels; level++)

to me it makes for sense than i...
If the idea is to just build a list of each name seen, then don't try to push back an empty value and then assign to it from the real value. Just assign the real value:

std::vector<std::string> myLevels;for (int level = 0; level < numberOfLevels; ++level) {  std::string levelFileName;  inFile >> levelFileName;  myLevels.push_back(levelFileName);}


The push_back operation will simply copy the current value into a new "slot" at the end, and the file name will be reset in each iteration by the read.

Edit: That said, you couldn't do it with the char[40], because push_back would get passed a pointer to the array, which is what would be copied. You would end up wit h a vector full of copies of pointers to the same (local) char buffer, which at the end would contain whatever the last filename was (and then make things even worse by promptly going out of scope). If you're smart enough to be using std::vector, you should definitely be smart enough to use std::string. :)

This topic is closed to new replies.

Advertisement