Archived

This topic is now archived and is closed to further replies.

Pointer Scope Problem

This topic is 5653 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I have a globally defined vector:
std::vector gvLevelList;

Now I have code to load level names from a text file into this vector like so:
char szLevelName[26];
while(!LevelFile.eof())
{
LevelFile.getline(szLevelName, 26);
gvLevelList.push_back(szLevelName);
}

The problem is that when I leave the function that this is in, the data in szLevelName is destroyed, thus destroying the data in the vector. Can anyone tell me how to get around this problem? Thanks in advance for your assistance. k9

Share on other sites
Try creating the pointers on the heap:

    while(!LevelFile.eof()){   char *szLevelName = new char[26];   LevelFile.getline(szLevelName, 26);   gvLevelList.push_back(szLevelName);}

Of course you have to remember to delete each one in gvLevelList once you are finished with them.

------
Andrew

[edited by - acraig on December 4, 2002 9:06:13 PM]

Share on other sites
If you're using vector, why not use string?:

    std::vector<std::string> > gvLevelList;   char szLevelName[26];while(!LevelFile.eof()){   LevelFile.getline(szLevelName,26);   gvLevelList.push_back(szLevelName);}

HTH

[edited by - Evil Bill on December 4, 2002 9:22:21 PM]

Share on other sites
That worked. Thanks a ton!

k9

• 10
• 17
• 9
• 13
• 41