通过两种不同的方法显示不同的字符串大小

Different size of string showing when going by two different methods

本文关键字:字符串 显示 方法 两种      更新时间:2023-10-16

当我这样做时:

string s="hello";
cout<<sizeof(s);

然后它显示4作为答案,但当我去一些单独的值:

string s="hello";
cout<<sizeof(s[2]);

输出为1。根据这个输出,第1的答案应该是5,因为字符串中有5个字符。我哪里错了?(我在Ideone上运行)。

sizeof()返回指定参数类型编译时字节大小。

s变量是std::string类的一个实例,因此sizeof(s)返回std::string类本身的字节大小,在32位可执行文件中为4(在64位可执行文件中为8),因为std::string类包含单个数据成员,该成员是指向分配的字符数据的指针。如果您想知道在运行时为字符串分配了多少个字符,请改用std::string::size()方法。这将返回您正在寻找的5。

s[2]返回char,因此sizeof(s[2])返回char类型的字节大小,即1。

sizeof运算符给出给定类型或表达式占用的内存(以字节为单位)。对于基本类型,这很简单。对于类/结构,它返回结构本身的字段所占用的字节数,不一定指向数据;对于该类型的每个实例都是相同的。

参见此回答

例子:

sizeof(char) // 1
sizeof(9001) // sizeof(int), usually 4
struct mystring {
    const char* data;
};
mystring foo = {"foo"};
sizeof(mystring) // probably sizeof(const char*), depending on packing; let's say 4
sizeof(foo)      // will always be same as above; 4
foo.data = "cornbread is tasty";
sizeof(foo)      // the struct itself still takes up the same amount of space; 4