【问题标题】:sizeof for a matrix of stringssizeof 用于字符串矩阵
【发布时间】:2013-03-23 00:26:32
【问题描述】:

cmets 公平地解释了这一切。帮忙?

   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.

【问题讨论】:

    标签: c++ arrays matrix sizeof


    【解决方案1】:

    sizeof 为您提供传递给它的对象的大小(以字节为单位)。如果你给它一个std::string,它会给你std::string对象本身的大小。现在该对象为实际字符动态分配存储空间并包含指向它们的指针,但这不是对象本身的一部分。

    要获取std::string 的大小,请使用其size/length 成员函数:

    cout << aZOM[0][1].size() << " \n";
    

    sizeof("MoraDoraKora") 工作正常的原因是字符串文字"MoraDoraKora" 不是 std::string 对象。它的类型是“13 个数组constchar1”,所以sizeof 以字节为单位报告该数组的大小。

    【讨论】:

    • 注意;对于第一个,你得到一个 const char* 的大小?
    • 这似乎是更好的解释。 :)
    • @Skeen 你得到数组的大小是因为数组不作为sizeof的操作数进行数组到指针的转换。
    【解决方案2】:

    sizeof返回类型的大小,而不是指向的数据的大小。

    字符串通常是指向 char 的指针,其中链中最后一个 char 的值为 0。

    如果你想要字符串的实际大小,你可以使用aZOM[0][0].length()

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多