我是c ++的新手。我写了这个程序。
#include <iostream>
using namespace std;
int main(void) {
int x=24;
char y='A';
char* pchar=&y;
int* pint=&x;
cout <<"pchar= "<<hex<<&pchar<<endl;
cout <<"pint = "<<hex<<&pint<<endl;
cout <<endl;
cout <<"pchar= "<<hex<<pchar<<endl;
cout <<"pint = "<<hex<<pint<<endl;
pchar=NULL;
pint=NULL;
getchar();
return 0;
}
及其结果
你能帮助我理解为什么我不能在没有&
的情况下打印变量的地址吗?
我认为pchar
已经是y
的地址。
感谢
答案 0 :(得分:3)
当您使用char*
(就像您的变量pchar
)时,使用string overload of operator<<
function,当将其视为字符串时,它将打印字符,直到找到字符串终止符( '\0'
)。不幸的是,在这种情况下,pchar
只指向一个字符,因此您有未定义的行为,因为函数会在内存中查找未分配给您的字符。
要打印指针,您必须将其强制转换为void*
:
std::cout << "pchar = " << std::hex << reinterpret_cast<void*>(pchar) << '\n';
当您打印变量pchar
的地址(打印&pchar
时)时,它会起作用,因为表达式的类型为char**
,没有直接过载,并且而是使用通用指针重载(this reference中的案例7)。
答案 1 :(得分:2)
运营商&lt;&lt;将char *作为字符串处理。但您可以将代码更改为以下
cout <<"pchar= "<<hex<<(void*)pchar<<endl;
它应该工作。 我现在无法访问std代码,但cout实现应包含类似这样的内容
operator << (char* char_ptr)
{
//interpret char * as pointer to null-terminated string
... code to output string
}
因此,如果没有强制转换,就无法将char *作为地址打印出来。
答案 2 :(得分:1)
你需要
cout <<"pchar= "<<hex<<static_cast<void*>(pchar)<<endl;
打印pchar
的值(不是它的地址,即变量pchar
的地址,而不是它指向的地址)。
它的行为是这样的,因为std::ostream
(cout
的类型)有一个重载operator<<
,它需要char*
并专门处理它以打印出一个字符串。< / p>
答案 3 :(得分:1)
更改此声明
cout <<"pchar= "<<hex<<pchar<<endl;
到
cout <<"pchar= "<<hex<< ( const void * )pchar<<endl;
问题是当你这样写的时候
cout <<"pchar= "<<hex<<pchar<<endl;
编译器将pchar视为字符串第一个元素的地址,并尝试输出该字符串。有一个重载的运算符&lt;&lt;对于char *
类型,在这种情况下调用它。
答案 4 :(得分:0)
pchar
值是y
的地址。因此,如果您打印pchar
,则会打印y
的地址。 &pchar
,它会打印pchar
的地址。请记住pchar
也有一些地址。