字符串矩阵的Sizeof
sizeof for a matrix of strings
注释很好地解释了这一切。帮助吗?
string aZOM[][2] = {{"MoraDoraKora", "PleaseWorkFFS"},{"This is a nother strang.", "Orly?"}};
cout << sizeof("MoraDoraKora") <<" n";
//Obviously displayes the size of this string...
cout << sizeof(aZOM[0][0]) << " n";
//here's the problem, it won't display the size of the actual string... erm, what?
string example = aZOM[0][0];
cout << example << " n";
cout << aZOM[0][1] << " n";
//Both functions display the string just fine, but the size of referencing the matrix is the hassle.
sizeof
以字节为单位给出传递给它的对象的大小。如果你给它一个std::string
,它会给你std::string
对象本身的大小。现在,该对象可以动态地为实际字符分配存储空间,并包含指向它们的指针,但这不是对象本身的一部分。
获取std::string
的大小,使用size
/length
成员函数:
cout << aZOM[0][1].size() << " n";
sizeof("MoraDoraKora")
工作正常的原因是字符串字面值"MoraDoraKora"
是而不是 std::string
对象。它的类型是"array of 13 const
char1
",因此sizeof
以字节为单位报告该数组的大小。
sizeof
返回类型的大小,而不是指向的数据的大小。
string通常是指向char的指针,其中链中的最后一个char的值为0。
如果您想要字符串的实际大小,您可以使用aZOM[0][0].length()