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!
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.
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.
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.
char* means a pointer to a character. In C strings are an array of characters terminated by the null character.
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*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With