The address of character type variable

后端 未结 3 716

Here is just a test prototype :

#include 
#include 
using namespace std;

int main()
{
   int a=10;
   char b=\'H\';
   string          


        
相关标签:
3条回答
  • 2021-01-20 11:36

    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)
    
    0 讨论(0)
  • 2021-01-20 11:36

    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)
    
    0 讨论(0)
  • 2021-01-20 11:50

    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 )
    
    0 讨论(0)
提交回复
热议问题