Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

map

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!

like image 481
Mark.A Avatar asked Apr 05 '12 20:04

Mark.A


People also ask

What's difference between char[] and char* s in C?

Difference between char s[] and char *s in CThe s[] is an array, but *s is a pointer. For an example, if two declarations are like char s[20], and char *s respectively, then by using sizeof() we will get 20, and 4. The first one will be 20 as it is showing that there are 20 bytes of data.

What is the difference between char * array and char array []?

The fundamental difference is that in one char* you are assigning it to a pointer, which is a variable. In char[] you are assigning it to an array which is not a variable.

Why use char* in C?

The statement 'char *s = “geeksquiz”' creates a string literal. The string literal is stored in the read-only part of memory by most of the compilers. The C and C++ standards say that string literals have static storage duration, any attempt at modifying them gives undefined behavior.

What does char* mean in C?

char* means a pointer to a character. In C strings are an array of characters terminated by the null character.


2 Answers

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*.

like image 138
hmjd Avatar answered Oct 19 '22 19:10

hmjd


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 image 34
Russell Borogove Avatar answered Oct 19 '22 17:10

Russell Borogove