This question already has answers here:
Why is address of char data not displayed?
(8个答案)
5年前关闭。
我正在尝试使用char数组,然后尝试运行此程序:
而且我不断得到这些输出:
这里到底发生了什么?我期待十六进制值。
(8个答案)
5年前关闭。
我正在尝试使用char数组,然后尝试运行此程序:
#include <iostream>
using namespace std ;
int main ( )
{
char *str = "Hello!" ;
cout << &str[0] << endl ;
cout << &str[1] << endl ;
cout << &str[2] << endl ;
cout << &str[3] << endl ;
cout << &str[4] << endl ;
return 0 ;
}
而且我不断得到这些输出:
Hello!
ello!
llo!
lo!
o!
这里到底发生了什么?我期待十六进制值。
最佳答案
当您获取数组元素的地址时,您将获得一个指向数组的指针。
在c++
中,像c
一样,字符数组(或指向字符的指针)被解释为字符串,因此字符被打印为字符串。
如果需要地址,只需将演员表添加到(void *)
。
#include <iostream>
using namespace std ;
int main ( )
{
const char *str = "Hello!" ;
cout << (void*) &str[0] << endl ;
cout << (void*) &str[1] << endl ;
cout << (void*) &str[2] << endl ;
cout << (void*) &str[3] << endl ;
cout << (void*) &str[4] << endl ;
return 0 ;
}