为什么即使内容更改,字符串变量的sizeof()总是返回相同的数字? [英] Why sizeof() of a string variable always return the same number even when content changes?

查看:34
本文介绍了为什么即使内容更改,字符串变量的sizeof()总是返回相同的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当简单的问题,但令人困惑.

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 ++标准定义单个 char 的大小为1

If you have a character array, say char c[6] then the type of c is an array of 6 chars. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆