Char pointer pointing to a Char array instead of a single char?

When I use the char pointer to point to a single char, it seems to end up pointing to a char array. What is wrong here?

 #include <iostream>
 #include <map>

 using namespace std;

 int main() {

     char first = 'a';
     char second = 'b';
     char third = 'c';

     map<char, char *> myMap;

     myMap['a'] = &first;
     myMap['b'] = &second;
     myMap['c'] = &third;

     cout << myMap['a'] << endl; // ends up printing 'abc' or 'cba'

     system("pause");
     return 0;    
 }
+3
source share
1 answer

operator<<overloading char*expects a pointer to the zero end of the character array, so that it knows where the line ends. It so happened that your variables charwere allocated contiguously in memory and that after them 0 bytes followed. However, the code causes undefined behavior.

To print a single char, look for a pointer:

cout << *myMap['a'] << endl;
+6
source

All Articles