C ++中字符串文字的数据类型是什么? [英] What is the datatype of string literal in C++?
问题描述
我对字符串文字的数据类型感到困惑.是const char *
还是const char
?
I'm confused about the datatype of a string literal. Is it a const char *
or a const char
?
推荐答案
它是一个const char[N]
(与char const[N]
是相同的东西),其中N
是字符串加上一个终止符NUL
的字符串(如果您已经定义了字符串的长度"(已经包括NUL
),则为字符串的长度).
It is a const char[N]
(which is the same thing as char const[N]
), where N
is the length of the string plus one for the terminating NUL
(or just the length of the string if you define "length of a string" as already including the NUL
).
这就是为什么您可以执行sizeof("hello") - 1
获取字符串中的字符数的原因(包括任何嵌入的NUL
);如果它是一个指针,它将不起作用,因为它始终是系统上指针的大小(减一).
This is why you can do sizeof("hello") - 1
to get the number of characters in the string (including any embedded NUL
s); if it was a pointer, it wouldn't work because it would always be the size of pointer on your system (minus one).
这篇关于C ++中字符串文字的数据类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!