字符串数组上的 C++ sizeof 在传递给函数时不返回预期结果

C++ sizeof on string array not returning expected results when passed to a function

正在尝试动态查找数组的大小。在 main() 中获取大小工作正常,但当我将它传递给 GetSize 函数时却没有。

#include <iostream>
#include <string>

using namespace std;

string GetSize(string array[]);

int main()
{
  string array[] = {"A", "B", "C", "D", "E"};
  int ARRAY_SIZE = (sizeof(array) / sizeof(array[0]));

  cout << "Total Size: " << sizeof(array) << endl;
  cout << "Single Element Size: " << sizeof(array[0]) << endl;

  // Pass the array as an argument to GetSize()
  GetSize(array);
}

string GetSize(string array[])
{
  // Get size of the array
  int ARRAY_SIZE = (sizeof(array) / sizeof(array[0]));

  cout << "Size of array is: " << sizeof(array) << endl;
  cout << "Size of 1st element is: " << sizeof(array[0]);    
}

输出

// Total Size: 160
// Single Element Size: 32
// Size of array is: 8
// Size of 1st element is: 32

我不知道为什么总大小和数组大小之间存在差异。

Repl 沙盒: https://repl.it/@phreelyfe/Size-Of-Error

template <typename T, std::size_t N>
constexpr std::size_t getArrSize (const T(&)[N])
 { return N; }

?

我的意思是:不同的数组,不同的大小,是不同的类型。

所以你必须明确传入参数的大小。

当你写

string GetSize(string array[])

编译器将 string array[] 视为 string * array,因此您得到 sizeof(array) 作为指针 (8) 的大小。

main()sizeof(array)string[5] 的大小,所以 160。