我正在尝试使用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 ;
}
Run Code Online (Sandbox Code Playgroud)
我一直得到这些输出:
Hello!
ello!
llo!
lo!
o!
Run Code Online (Sandbox Code Playgroud)
到底发生了什么?我期待十六进制值.
获取数组元素的地址时,会得到一个指向数组的指针.
在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 ;
}
Run Code Online (Sandbox Code Playgroud)