字符类型变量的地址

The address of character type variable

本文关键字:地址 类型变量 字符      更新时间:2023-10-16

这里只是一个测试原型:

#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;
}

为什么变量"b"的地址是字符类型,而不是打印?

<<有一个重载,它获取指向char的指针并将其解释为终止的 C 样式字符串。将其用于任何其他char的地址将出现可怕的错误。

相反,转换为

无类型指针,这样<<就不会变得太聪明:

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

表达式&b的类型为char *。当运算符<<对 char * 类型的对象使用时,它会将其视为字符串并将其输出为字符串。要输出您应该写的地址

( void * ) &b

reinterpret_cast<void *>( &b )

代码中的<<运算符在第 11 C++重载。它与任何其他类型的intstring不冲突,但它需要指向char的指针,如果使用,可能会产生不希望的结果。

你可以这样做:-

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