评论很好地解释了这一切。帮忙?
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
对象。它的类型是“13 个 const
char1
的数组”,因此 sizeof
报告该数组的大小(以字节为单位)。
关于c++ - 字符串矩阵的 sizeof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15581904/