Strange std::map issue involving char*

Started by
3 comments, last by neurokaotix 20 years, 3 months ago
I''m having a bit of trouble here with std::map and I hope someone can give me an explanation. To sum up the problem, I''m storing pointers in a map and using a char* name as the reference to them. I can use text incapsulated in quotes as the first parameter and I''m able to retrieve the pointer just fine, but I cannot use a char* variable with the name stored in it. Let me post some code for clarification:

std::map<char*, mFileSystemInterface*> filesystems;
        
//this works:

this->filesystems.insert(std::make_pair((char*)"zip", zipfilesystem));
        
//this does not work:

char* MyName = "zip"
this->filesystems.insert(std::make_pair(MyName, zipfilesystem));
Here is my pointer retrieving code:

std::map<char*, mFileSystemInterface*>::iterator it;
it = filesystems.find(fsname);
if (it == filesystems.end())
{ 
        //It couldn''t find the pointer

        mLog::l->Write("%s didn''t work", fsname);
        it = filesystems.find("stdio");
        return it->second;
	
}
else
{
        //It found the pointer

        mLog::l->Write("%s worked", fsname);
        return it->second;
}
For some odd reason I can retrieve the pointer if I added the name via (char*)"zip", but if I add it with MyName it just refuses to work. Does anyone know why this is? MindEngine Development http://medev.sourceforge.net
Advertisement
You should generally not use char* as key to the map. Use std::string instead. The map uses operators like > and == to compare the keys; and for char*, they just compare the pointers and not the content.
Use std::string and this won''t happen.



"THE INFORMATION CONTAINED IN THIS REPORT IS CLASSIFIED; DO NOT GO TO FOX NEWS TO READ OR OBTAIN A COPY." , the pentagon
Mostly using char * won''t do what you want. For example comparison will usually be done using the == operator, which won''t work for C-style strings.
Thanks guys

MindEngine Development
http://medev.sourceforge.net

This topic is closed to new replies.

Advertisement