为什么即使内容更改,字符串变量的sizeof()总是返回相同的数字? [英] Why sizeof() of a string variable always return the same number even when content changes?
问题描述
这是一个相当简单的问题,但令人困惑.
This is a rather simple problem but is pretty confusing.
string R = "hhhh" ;
cout<< sizeof( R )<<endl;
输出:
4
变量:
string R ="hhuuuuuuhh";cout<<sizeof(R)<
OUTPUT2:
string R = "hhuuuuuuhh" ; cout<< sizeof( R )<
OUTPUT2:
4
出了什么问题?我应该改用char数组吗?
What is going wrong ? Should I use char array instead ?
推荐答案
认为 sizeof
是编译时可评估的.它计算类型的大小,而不是内容的大小.您甚至可以编写 sizeof(std :: string)
,与 sizeof(foo)
完全相同,对于任何 std::string
instance foo
.
Think of sizeof
being compile-time evaluable. It evaluates to the size of the type, not the size of the contents. You can even write sizeof(std::string)
which will be exactly the same as sizeof(foo)
for any std::string
instance foo
.
要计算 std :: string
中的字符数,请使用 size()
.
To compute the number of characters in a std::string
, use size()
.
如果您有一个字符数组,请说出 char c [6]
,那么 c
的 type 是一个 array 6个 char
.因此, sizeof(c)
(在编译时为已知)将为6,因为C ++标准定义单个
If you have a character array, say char c[6]
then the type of c
is an array of 6 char
s. So sizeof(c)
(known at compile-time) will be 6 as the C++ standard defines the size of a single char
to be 1.
这篇关于为什么即使内容更改,字符串变量的sizeof()总是返回相同的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!