不能在c ++中打印指针的地址 [英] can not print address of a pointer in c++
问题描述
我是c ++的新手。我写了这个程序。
I'm new in c++. I wrote this program.
#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;
}
及其结果
and its result
你能帮我理解为什么我不能打印没有&
的变量的地址?
我认为 pchar
已经是 y
的地址。
Can you help me to understand why I can't print the address of variables without &
?
I think pchar
is already the address of y
.
感谢
推荐答案
当您使用 char *
(像你的变量 pchar
)使用运算符< <
函数的字符串重载,并且当将其视为字符串时,它将打印字符,直到找到字符串终止符字符c $ c>'\0')。不幸的是,在这种情况下, pchar
只指向一个字符,所以你有未定义的行为,因为函数出去寻找内存中的字符未分配
When you use a char*
(like your variable pchar
) the string overload of operator<<
function is used, and when treating it as a string it will print characters until it find the string terminator character ('\0'
). Unfortunately in this case pchar
points only to a single character, so you have undefined behavior as the function goes out looking for characters in memory not allocated to you.
要打印指针,必须将其转换为 void *
:
To print a pointer you have to cast it to void*
:
std::cout << "pchar = " << std::hex << reinterpret_cast<void*>(pchar) << '\n';
当您打印变量 pchar
(当你打印& pchar
)时,因为表达式的类型是 char **
它们没有直接重载,而是使用通用指针重载(此参考中的案例7) )。
It works when you print the address of the variable pchar
(when you print &pchar
) because then the type of the expression is of type char**
which have no direct overload, and instead uses the generic pointer overload (case 7 in this reference).
这篇关于不能在c ++中打印指针的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!