如果 x 是指针,&x 与 x 有何不同?
所以...我有以下代码:
int main(void)
{
const char *s="hello, world";
cout<<&s[7]<<endl;
return 0;
}
它打印“world”...但是我不明白为什么会这样:
int main(void)
{
const char *s="hello, world";
cout<<s[7]<<endl;
return 0;
}
只会打印“w”(我所做的只是去掉了&符号),但我认为是“地址”运算符......这让我想知道为什么你需要它以及它的功能是什么?
So...I have the following code:
int main(void)
{
const char *s="hello, world";
cout<<&s[7]<<endl;
return 0;
}
and it prints "world"...however I don't understand why this:
int main(void)
{
const char *s="hello, world";
cout<<s[7]<<endl;
return 0;
}
only will print "w" (all I changed is got rid of the ampersand), but I thought that was the "address of" operator...which makes me wonder why you need it and what it's function is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
s[7]
是字符'w'
,因此&s[7]
就变成了地址字符'w'
。当您将char*
类型的地址传递给cout
时,它会打印从该字符开始到空字符(即结尾)的所有字符。字符串,即它继续从'w'
开始打印字符,直到找到\0
。这就是world
的打印方式。就像这样,
输出:
但是,如果你想打印
s[7]
的地址,即&s[7]
的值,那么你必须这样做:现在我们传递一个
void*
类型的地址,因此cout
将无法推断出它用来推断char*
的内容> 输入地址。void*
隐藏有关地址内容的所有信息。因此,cout
只是打印地址本身。毕竟,这才是它最多得到的。在线演示:http://www.ideone.com/BMhFy
s[7]
is the character'w'
, so&s[7]
becomes the address of the character'w'
. And when you pass an address ofchar*
type tocout
, it prints all characters starting from the character to the null character which is end of the string i.e it continues to print characters from'w'
onward till it finds\0
. That is howworld
gets printed.Its like this,
Output:
However, if you want to print the address of
s[7]
, i.e value of&s[7]
, then you've to do this:Now we pass an address of
void*
type, socout
wouldn't be able to infer what it used to infer withchar*
type address.void*
hides all information regarding the content of the address. Socout
simply prints the address itself. After all, that is what it gets at the most.Online demonstration : http://www.ideone.com/BMhFy
你的标题根本不符合你的问题。
由于
s
是指向 char(又名 C 风格字符串)的指针,因此s[7]
是一个 char。由于s[7]
是一个 char,因此&s[7]
是一个指向 char 的指针(也称为 C 风格字符串)。Your title doesn't match your question... at all.
Since
s
is a pointer to char (aka C-style string),s[7]
is a char. Sinces[7]
is a char,&s[7]
is a pointer to char (aka C-style string).s[7] 是一个字符。 (您可以对指向数组的指针进行索引,就好像它只是数组的名称一样)。
&s[7] 是指向索引 7 处的字符的指针。它的类型是 char*,因此流插入器将其视为 char*。
s[7] is a character. (You can index into pointers to an array as if it was just the name of the array).
&s[7] is a pointer to the character at index 7. it's type is char*, so the stream inserter treats it like a char*.