Why does the following code produce the output "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. 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.
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). Therefore when you dereference it, it will get you the first char of your "string".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.