Tuesday, September 6, 2016

Why C++ would not print the memory address of a char.

If I said that "C++ is not able to print pointer value of a char", would you believe it?? I also confused at first, but found the reason.

char ch ='a';
int num=0;
string str = "abc";

cout << &ch << endl;
cout << &num << endl;
cout << &str << endl;

If you compile and run this code it will print character "a" instead of address of ch variable.

Why is this happening..?

Later found that it only happens with  << operator.

When you are taking the address of b, you get char *. operator<< interprets that as a C string, and tries to print a character sequence instead of its address because there is a special overload in operator<<.

How to print the address..?

If we want to print the char * value then we have to cast it into (void*) as follows.

char ch ='a';
int num=0;
string str = "abc";

cout << (void *)&ch << endl;
cout << &num << endl;
cout << &str << endl;
cout << &st << endl;

--This will print the address of char variable

No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...