When I use a char pointer to point to a single char it seems to end up pointing to a char array instead. What's going 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;
}
operator<< overload for char* expects a pointer to a null terminated array of characters so that it knows where the string ends. It just so happens that your char variables were allocated contiguously in memory and that a 0 byte follows them. The code invokes undefined behaviour though.
To print a single char, dereference the pointer:
cout << *myMap['a'] << endl;
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