[英]what happens when you dereference a string in c++
Why does the following code produce the output "h"? 为什么以下代码产生输出“ h”? I do not understand it.
我不明白。 Since it's dereferencing it, shouldn't it print out its memory address?
由于它正在取消引用,因此它不应该打印出其内存地址吗?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << *("hello");
return 0;
}
“ hello”的计算结果是指向字符串第一个字符的指针,对它的解引用将对该字符串的结果进行赋值。
A string literal ( "hello"
in this case) is a array of const char
of size N
where N
is the number of characters plus a null terminator. 字符串文字(在这种情况下为
"hello"
)是大小为N
的const char
数组,其中N
是字符数加上空终止符。 That array can decay to a pointer to the first element. 该数组可以衰减为指向第一个元素的指针。 When you dereference that pointer you now have the first element of the array, which is a character.
现在,当取消引用该指针时,您将拥有数组的第一个元素,即一个字符。 That is why
h
is printed as you gave cout
a character. 这就是为什么在给
cout
字符时打印h
原因。
The string is saved at some memory location in the binary (when the source is compiled). 该字符串保存在二进制文件中的某个存储位置(在编译源代码时)。
A string like "hello"
is converted to a char *
(pointer to char). 像
"hello"
这样的字符串将转换为char *
(指向char的指针)。 Therefore when you dereference it, it will get you the first char of your "string". 因此,当您取消引用它时,它将获得“字符串”的第一个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.