【发布时间】:2020-06-06 16:36:04
【问题描述】:
我正在尝试编译以下代码:
#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 运算符在同一个数组上工作,在两个不同的点给出两个不同的输出?请解释。
【问题讨论】:
-
声明参数时,数组实际上是指针。因此,
show1函数的参数text1真正声明为string* text1。获取指针的sizeof是指针本身的大小,而不是它可能指向的大小。请改用std::vector或std::array。 -
提醒:
sizeof(string)是std::string结构的大小,而不是字符串中文本的大小。另请参阅std::string::length()。 -
谢谢它解决了我的疑惑。