C++中打印变量或对象的地址

  C语言中,我们可以使用格式控制符%p来打印一个变量的地址,如下:

int a = 0;
char * p = "hello";
printf("变量a的地址: %p\n", &a);    // 输出变量a的地址
printf("字符串的地址:%p\n", p);     // 输出字符串的地址

  C++中,可以使用如下形式:

int a = 0;
const char * p = "hello";
cout << "变量a的地址: " << &a << endl;                           // 变量a的地址
cout << "变量a的地址: " << static_cast<void *>(&a) << endl;      // 变量a的地址
cout << "字符串 " << p << endl;                                 // 字符串内容,即"hello"
cout << "字符串的地址 " << static_cast<const void *>(p) << endl; // 字符串的地址

  C++中,如果变量或对象是指针类型,可以使用static_cast转换一下来得到其地址,如下:

T * ptr = 0;
cout << static_cast<void *>(ptr) << endl;

猜你喜欢

转载自blog.csdn.net/linuxwuj/article/details/81562661
今日推荐