当我运行此代码时:
#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]
。这是怎么回事? 最佳答案
在第二种方法中,将数组按值传递给函数。它衰减到一个指针,因此大小是指针的大小(在您的情况下为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::vector
或 std::array
可能会更好。关于c++ - sizeof函数在函数中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34216022/