通过两种不同的方法显示不同的字符串大小
Different size of string showing when going by two different methods
当我这样做时:
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
相关文章:
- 字符串-C++后显示的随机字符
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 显示字符串的集合和子集
- 在将字符插入 2d 字符串时如何不显示空字符?
- 两个数组,int 和 string,如何显示带有对应 int 的字符串?
- 为什么我的 cout 在输出中没有显示字符串?
- 为什么在为其分配编号后无法显示我的字符串值?
- 分段故障 11,从类函数显示动态 C 字符串
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- isPalindrome不显示输出,isPalindrome函数未使用字符串输入作为字符串参数进行测试
- 输出显示多个带整数的字符串值
- 字符串显示上的智能感知:npos = 18446744
- 如何从显示板将字符显示为字符串?
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 使用宏显示宏的字符串化内容
- 我将如何将数组的显示从数字更改为字符串C++
- 如何让我的构造函数和函数工作,以便我的 main() 能够同时显示字符串和 int 数据
- C 我将如何在字符串中显示字符作为数字
- 如何使用另一个字符串显示三个浮点数的最大值?
- 如何比较"4A4B4C"(字符串显示十六进制值)实际字符串"JKL"