Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char pointer pointing to char array instead of single char?

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;    
 }
like image 336
jonathanpaul Avatar asked Oct 21 '25 20:10

jonathanpaul


1 Answers

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;
like image 87
jrok Avatar answered Oct 24 '25 10:10

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!