The address of character type variable

感情迁移 提交于 2019-12-04 04:11:41

问题


Here is just a test prototype :

#include <iostream>
#include <string>
using namespace std;

int main()
{
   int a=10;
   char b='H';
   string c="Hamza";

   cout<<"The value of a is : "<<a<<endl;
   cout<<"The value of b is : "<<b<<endl;
   cout<<"The value of c is : "<<c<<endl<<endl;

   cout<<"address of a : "<<&a<<endl;
   cout<<"address of b : "<<&b<<endl;
   cout<<"address of c : "<<&c<<endl;

   return 0;
}

Why the address of variable 'b', which is of character type, not printing?


回答1:


The << operator in your code is overloaded in C++ 11. It doesn't conflict with any of other types like int or string, but it takes pointer to char which if used can produce undesired results.

You can do it like:-

cout << static_cast<void*>(&b)



回答2:


There is an overload for << which takes a pointer to char and interprets it as a terminated C-style string. Using this for the address of any other char will go horribly wrong.

Instead, convert to a typeless pointer so that << doesn't get too clever:

cout << static_cast<void*>(&b)



回答3:


Expression &b has type char *. When operator << used fo an object of type char * it considers it as a string and outputs it as a string. To output the address you should write

( void * ) &b

or

reinterpret_cast<void *>( &b )


来源:https://stackoverflow.com/questions/20032866/the-address-of-character-type-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!