简体   繁体   中英

C++ map::find char * vs. char []

I'm using C++ map to implemented a dictionary in my program. My function gets a structure as an argument and should return the associated value based on structure.name member which is char named[32] . The following code demonstrates my problem:

map <const char *, const char *> myMap;
myMap.insert(pair<const char *, const char *>("test", "myTest"));

char *p = "test";
char buf[5] = {'\0'};
strcpy(buf, "test");

cout << myMap.find(p)->second << endl; // WORKS
cout << myMap.find("test")->second << endl; // WORKS
cout << myMap.find(buf)->second << endl; // DOES NOT WORK

I am not sure why the third case doesn't work and what should I do to make it work. I debugged the above code to watch the values passed and I still cannot figure the problem.

Thanks!

Pointer comparison, not string comparison, will be performed by map to locate elements. The first two work because "test" is a string literal and will have the same address. The last does not work because buf will not have the same address as "test" .

To fix, either use a std::string or define a comparator for char* .

The map key is a pointer, not a value. All your literal "test" strings share storage, because the compiler is clever that way, so their pointers are the same, but buf is a different memory address.

You need to use a map key that has value equality semantics, such as std::string , instead of char* .

Like was mentioned you are comparing on the address not the value. I wanted to link this article:

Is a string literal in c++ created in static memory?

Since all the literals had the same address this explains why your comparison of string literals worked even though the underlying type is still a const char * (but depending on the compiler it may not ALWAYS be so)

Its because by buf[5] you are allocating the memory pointed by buf but when u use 'p' pointer it points to the same memory location as used by map. So always use std::string in key instead of pointer variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM