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