1

So, I am trying to learn map in C++. I put the type as std:: map <const char *, int> to a variable month.

Say, the data is month["Jul"] = 7;

When I tried to retrieve the value directly

printf("%d", month["Jul"]);

It succeeds and outputs the value.

7

Trying with another variable succeeds too.

const char *p = "Jul";
printf("%d", month[p]); // 7

But strange behavior happens when I tried to assign it with a given input.

const char in_month[3];
scanf("%s", in_month);
print("%d". month[in_month]);

It retrieves (null)

0

Did I do something forbidden here or was there a step that I missed?

Zukaru
  • 320
  • 2
  • 11
  • Have you tried using C++ idioms instead of C idioms? – Eljay Jun 12 '20 at 01:28
  • @Eljay if you refer to ```std:: cin``` or ```std:: cout```, I've done and it results in the same. – Zukaru Jun 12 '20 at 01:47
  • `std::string`, `std::cin`, `std::cout`, not using `printf`, not using `const char*`, not using `scanf`. A [mcve] would be useful, too. – Eljay Jun 12 '20 at 02:16

1 Answers1

1

When you use const char* as the key, std::map will compare on the pointer directly, but not the content pointed by the pointer. For c-style string literals, the identical string literals might be compared as equal, but this is not guaranteed.

The compiler is allowed, but not required, to combine storage for equal or overlapping string literals. That means that identical string literals may or may not compare equal when compared by pointer.

When you use the array in_month, after converting to pointer it points to different things, then the pointer comparison result is false.

Better to use std::string instead as std:: map <std::string, int>. std::string has well-defined comparison operator which compares based on the content of string.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • I agree with you. I encounter some strange outputs with the given input chars. I would go with your advice using ```std:: string``` before my codes turn into spaghetti. – Zukaru Jun 12 '20 at 01:44
  • 2
    @NabilAsykar The strange outputs? It might come from the declaration of the array `in_month`, which contains 3 elements and can't stroe string literal `"Jul"`, which has 4 `char`s including the null terminator `'\0'`. – songyuanyao Jun 12 '20 at 01:53
  • yup doesn't work I setup a test online it fails. https://onlinegdb.com/r1tcJ_xaU – SSpoke Jun 12 '20 at 02:59