1

How it is possible that the same key is added twice in map? shouldn't it override the value in case the value was changed?

static map<const char *, int> lMap;
    const char * msg = "hhhhh";

    char *buf = (char *) malloc(5);
    strcpy(buf, msg);

    lMap.insert(make_pair(buf, 85));
    buf = (char *) calloc(5, sizeof (char));

    strcpy(buf, msg);
    lMap.insert(make_pair(msg, 85));

    cout << "size: " << lMap.size() << endl;
    map<const char *, int>::const_iterator it2;
    for (it2 = lMap.begin(); it2 != lMap.end(); ++it2) {
        cout << it2->first << " | " << it2->second << endl;
    }

printed result:

size: 2
hhhhh | 85
hhhhh | 85
15412s
  • 3,298
  • 5
  • 28
  • 38
  • 2
    As a side note: to be able to `strcpy` the string "hhhhh" you need 6, not 5 characters (5 for the `'h'`s and one for the terminating `'\0'`). – 6502 Jun 22 '16 at 07:29
  • 1
    [Using char* as a key in std::map](http://stackoverflow.com/questions/4157687/using-char-as-a-key-in-stdmap?rq=1) – songyuanyao Jun 22 '16 at 07:29

3 Answers3

2

const char* is a pointer. Comparing two pointers with < compares the addresses they point to. By default, std::map uses < to compare keys. Which means that two different const char* objects are distinct keys, even if they happen to contain the same data when interpreted as a nul-terminated string.

You're writing C++, not C. If you want a string, use std::string, not a pointer to something which will hopefully be a nul-terminated buffer.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

You don't have the same key twice in the map. The key of the map is a char * (i.e. a pointer). You have two different pointer values that happen to point to identical strings.

The Dark
  • 8,453
  • 1
  • 16
  • 19
1
     static map<const char *, int> lMap;

The above statement maps int to const char* and not int to value pointed by const char*.

The map does not care what is pointed by the keys,it just cares that there are two different keys hence two entries are made.

Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34