c++ - 字符串矩阵的 sizeof

标签 c++ arrays matrix sizeof

评论很好地解释了这一切。帮忙?

   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/

相关文章:

ruby - 使用 Ruby 按值过滤 JSON 数组

java - 为矩阵上的随机元素设置值

python - Tensorflow中某些元素的逆序

c++ - 如何检查 T 是否为聚合类型?

c++ - g++优化使程序无法运行

java - 以矩阵格式打印二维数组

r - 将 lines() 应用于数据框/矩阵的列;每条线都有不同的颜色

c++ - 单例:应该如何使用

C++事件驱动示例

php - 如果求和时单个数组两侧的值相等,则查找索引