字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
Sizeof operator on string array is giving different output in C++
我正在尝试编译以下代码:
#include <iostream>
using namespace std;
void show1(string text1[]) {
cout << "Size of array text1 in show1: " << sizeof(text1) << endl;
}
int main() {
string text1[] = {"apple","melon","pineapple"};
cout << "Size of array text1: " << sizeof(text1) << endl;
cout << "Size of string in the compiler: " << sizeof(string) << endl;
show1(text1);
return 0;
}
输出如下所示:
Size of array text1: 96
Size of string in the compiler: 32
Size of array text1 in show1: 8
我无法理解,为什么 sizeof 运算符在同一个数组上工作,在两个不同的点给出两个不同的输出?请解释一下。
sizeof()
运算符返回对象的编译时大小。这意味着,如果您的类型在运行时从堆分配内存块,则sizeof()
不会考虑该内存。
对于您的第一种情况,即
string text1[] = {"apple","melon","pineapple"};
您有一个包含 3 个字符串的数组,因此sizeof
应返回3*sizeof(std::string)
.(3*32 = 96 在您的情况下(
对于第二种情况:
sizeof(string)
它应该简单地打印字符串的大小。(在您的情况下为 32(。
最后,对于最后一种情况,不要忘记数组是使用 C/C++ 中的指针传递的。因此,您的参数只是一个指针,sizeof()
应该在您的机器上打印指针的大小。
编辑:正如@ThomasMatthews在评论中提到的,如果您有兴趣获取字符串的实际大小(即其中的字符数(,您可以使用std::string::length()
或std::string::size()
。
尝试使用成员函数 'size'。
编写以下代码:
#include <iostream>
using namespace std;
void show1(string text1[])
{
cout << "Size of array text1 in show1: " << text1->size() << endl;
}
int main()
{
string text1[] = {"apple","melon","pineapple"};
cout << "Size of array text1: " << text1->size() << endl;
cout << "Size of string in the compiler: " << sizeof(string) << endl;
show1(text1);
return 0;
}
描述:
std::vector
有一个成员函数size()
。也是std::string
。在std::vector
返回向量(所有元素(的大小。Instd::string
返回数组中的所有元素。
相关文章:
- 以天C++为单位的两个时间戳之间的差异
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 编写以 C++ 为单位返回值的函数
- 以C++为单位进行运行长度编码
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- arr[n] 是否以 C++ 为单位打印数组的长度?
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 以 C++ 为单位具有输出限制的排列
- 以 GDB 为单位指定浮点精度
- 整数数据如何以位为单位存储在内存中?不是右对齐吗?
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- 如何在没有硬编码的情况下以C++为单位获取类数组的长度?
- 指针引用的生存期(以 C++为单位)
- 以字符为单位设置控制台大小
- 函数,以 C++ 为单位输出整数的位数之和
- 以 C++ 为单位的 lambda 输出
- 以 C++ 为单位的浮点数学运算输出
- 以 XLL 为单位获取调用方定义的输出数组尺寸