【发布时间】: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]。怎么回事?
【问题讨论】: