当我运行此代码时:
#includeusing 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) }
如果您希望能够传递任意长度的数组,我建议通过模板化函数通过引用传递:
templatevoid f(T (&arr)[N]) { // N gives you the size in the body }
如果您仍想通过值传递,那么"检测"其大小的唯一方法是将另一个参数传递给表示数组大小的函数.然而,这可能会引起很多麻烦,并且容易出错.你可能更好std::vector
或更好std::array
.