H
H
herfleisch2011-11-13 16:57:10
C++ / C#
herfleisch, 2011-11-13 16:57:10

Error in accessing map through operator []?

I'm sorry, the question is most likely completely lamer, but I'm encountering STL for the first time.
There is a code:

char* packetType = "SLogin";
RegisteredEventFn fnForCall = registeredEvents[packetType];
// fnForCall == <указатель на функцию>

In this case, everything works like clockwork. But it's not like this:
char* packetType = (char*)txePacket-&gt;Attribute(&quot;type&quot;);
// packetType указывает на строку &quot;SLogin&quot;, строка заканчивается '\0'
RegisteredEventFn fnForCall = registeredEvents[packetType];
// fnForCall == NULL

Why is NULL returned to me in the second case? After all, the pointer to the string is passed to the operator [] in both the first and second cases. Moreover, it doesn't matter whether it is a const char* or char* pointer - the effect is still the same.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gribozavr, 2011-11-13
@herfleisch

In the second case it doesn't work because char * are mapped by std::map as pointers. Naturally, two different strings (one constant, one from txePacket), albeit having the same values, are located at different addresses and therefore are not equal as pointers.
The question remains why it works in the first case. As an optimization, the compiler merges all identical string constants into one with the same address in a read-only section. Therefore, the literal string "foo" anywhere in the same translation unit will have the same address.
char *x = "...";you can not do it this way. Literal strings areconst char *.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question