Jac*_*own 3 c++ pointers ampersand
所以...我有以下代码:
int main(void)
{
const char *s="hello, world";
cout<<&s[7]<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它打印"世界"...但我不明白为什么这样:
int main(void)
{
const char *s="hello, world";
cout<<s[7]<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
只有将打印"W"(所有我改变是摆脱了符号的),但我认为这是运营商"的地址" ......这使我想知道为什么你需要它,它的功能是?
Naw*_*waz 10
s[7]是字符'w',所以&s[7]变成了地址的字符'w'.当你传递一个char*类型的地址时cout,它会打印从字符开始的所有字符到字符串结尾的空字符,即它继续从'w'前往打印字符直到找到它\0.这就是world打印的方式.
就像这样,
const char *s="hello, world";
const char *pchar = &s[7]; //initialize pchar with the address of `w`
cout<< pchar <<endl; //prints all chars till it finds `\0`
Run Code Online (Sandbox Code Playgroud)
输出:
world
Run Code Online (Sandbox Code Playgroud)
但是,如果要打印地址s[7],即值&s[7],那么你要这样做:
cout << ((void*)&s[7]) << endl; //it prints the address of s[7]
Run Code Online (Sandbox Code Playgroud)
现在我们传递一个void*类型的地址,因此cout无法推断它用于推断char*类型地址的内容.void*隐藏有关地址内容的所有信息.所以cout只需打印地址本身.毕竟,这就是它最多的东西.
在线演示:http://www.ideone.com/BMhFy