字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出

Sizeof operator on string array is giving different output in C++

本文关键字:为单位 输出 数组 sizeof 运算符 字符串 C++      更新时间:2023-10-16

我正在尝试编译以下代码:

#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返回数组中的所有元素。