【问题标题】:Sizeof operator on string array is giving different output in C++字符串数组上的 Sizeof 运算符在 C++ 中给出不同的输出
【发布时间】: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 运算符在同一个数组上工作,在两个不同的点给出两个不同的输出?请解释。

【问题讨论】:

标签: c++ c++11 ubuntu sizeof


【解决方案1】:

sizeof() 运算符返回对象的编译时大小。这意味着如果您的类型在运行时从堆中分配内存块,则sizeof() 不会考虑该内存。

对于您的第一种情况,即

 string text1[] = {"apple","melon","pineapple"};

你有一个包含 3 个字符串的数组,所以 sizeof 应该返回 3*sizeof(std::string)。 (在您的情况下为 3*32 = 96)

对于你的第二种情况:

sizeof(string)

它应该简单地打印字符串的大小。 (在您的情况下为 32)。

最后,对于最后一种情况,不要忘记在 C/C++ 中使用指针传递数组。因此,您的参数只是一个指针,sizeof() 应该在您的机器上打印指针的大小。

编辑:正如@ThomasMatthews 在 cmets 中提到的,如果您有兴趣获取字符串的实际大小(即其中的字符数),您可以使用 std::string::length()std::string::size().

【讨论】:

  • sizeof 不是函数,而是运算符。并且只有当它的操作数是一个类型时才需要括号,这使得它更不是一个函数。
【解决方案2】:

尝试使用成员函数 'size'。

写下这段代码:

#include <iostream>
using namespace std;
void show1(string text1[]) 
{
    cout << "Size of array text1 in show1: " << text1->size() << endl;
}

int main() 
{
    string text1[] = {"apple","melon","pineapple"};
    cout << "Size of array text1: " << text1->size() << endl;
    cout << "Size of string in the compiler: " << sizeof(string) << endl;
    show1(text1);
    return 0;
}

说明:

std::vector 有一个成员函数size()。还有std::string。在std::vector 返回向量的大小(所有元素)。在std::string 中返回数组中的所有元素。

【讨论】:

  • text1-size() 是语法错误。如果将其更改为text1-&gt;size(),它将编译但it doesn't show the size of the array。您是否故意发布错误答案?
  • 再一次,text1-&gt;size() 不显示数组的大小。传递给函数的数组衰减为指针。您正在打印数组中第一个 std::string 的大小。
  • 对不起,我不知道。此通知的 Tkanks。
猜你喜欢
  • 2018-01-19
  • 1970-01-01
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多