sizeof函数在函数中不起作用

sizeof Function not Working in Function

本文关键字:函数 不起作用 sizeof      更新时间:2023-10-16

当我运行此代码时:

#include <iostream>
using namespace std;
void PrintLengthOfArray(double arr[])
{
  int total_bytes = sizeof(arr);
  int data_type_bytes = sizeof(arr[0]);
  int length = total_bytes / data_type_bytes;
  cout << "method 2: n";
  cout << "total_bytes = " << total_bytes << "n";
  cout << "data_type_bytes = " << data_type_bytes << "n";
  cout << "length = " << length << "n";
}
int main()
{
  double arr[3] = {1,2,3};
  int total_bytes = sizeof(arr);
  int data_type_bytes = sizeof(arr[0]);
  int length = total_bytes / data_type_bytes;
  // first method
  cout << "method 1: n";
  cout << "total_bytes = " << total_bytes << "n";
  cout << "data_type_bytes = " << data_type_bytes << "n";
  cout << "length = " << length << "nn";
  // second method
  PrintLengthOfArray(arr);
}

我得到:

method 1: 
total_bytes = 24
data_type_bytes = 8
length = 3
method 2: 
total_bytes = 8
data_type_bytes = 8
length = 1

也就是说,这就像函数中的total_bytes = sizeof(arr)语句只计算单个元素的大小,或者只计算arr[0]。怎么回事?

在第二个方法中,按值将数组传递给函数。它衰减为一个指针,因此大小是指针的大小,在您的情况下是8字节。请注意,函数声明

f(double arr[])

甚至

f(double arr[3])

由编译器翻译成

f(double*)

将数组传递给函数并保持其大小的唯一有意义的方法是通过引用传递,例如

void f(double (&arr)[3]) 
{
    std::cout << sizeof arr << std::endl; // displays 3 * sizeof(double)
}

如果您希望能够传递任意长度的数组,我建议通过模板化函数进行引用传递:

template<typename T, size_t N>
void f(T (&arr)[N])
{
    // N gives you the size in the body
}

如果您仍然希望按值传递,那么"检测"其大小的唯一方法就是向函数传递一个表示数组大小的附加参数。然而,这可能会引起很多头痛,而且很容易出错。使用std::vectorstd::array可能会更好。