【问题标题】:sizeof Function not Working in Functionsizeof 函数在函数中不起作用
【发布时间】:2015-12-11 04:15:43
【问题描述】:

当我运行这段代码时:

#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 << "\n\n";

  // 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]。怎么回事?

【问题讨论】:

    标签: c++ arrays


    【解决方案1】:

    在第二种方法中,您将数组按值传递给您的函数。它衰减为指针,因此大小是指针的大小,在您的情况下为 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 可能会更好。

    【讨论】:

    • 我认为同样重要的是指出函数参数被调整为指针。
    • @vsoftco 好的,这是有道理的。有没有标准的方法来检查函数中数组的大小?
    • @bcf 如果按值传递,则不会。唯一的方法是通过引用传递,请参阅编辑。
    • @NickyC 不确定我完全理解你的意思。我提到“腐烂”成指针,你是不是在想别的?
    • @bcf 我会坚持使用标准容器。如果您不(不能)使用标准库容器,或者在您处理遗留代码的情况下,我已经看到了模板技巧。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    相关资源
    最近更新 更多