C++之数组作为函数的参数
数组作为函数的参数parameter
// Example program
#include <iostream>
const int SIZE = 5;
void show(int a[], int n){
using namespace std;
cout << "show:"<< sizeof(a) << endl; // 输出: 4 指针本身并没有指出 数组的长度 所以需要显式地传入数组的长度n
}
int main()
{
using namespace std;
int array[SIZE]={1,2,3,4,5};
cout << "main:"<< sizeof(array)<< endl; // 输出: 20
show(array,SIZE);
return 1;
}
第5行和第13行代码处的数组名都是指向同一个地址。但sizeof(array)
的值是20,sizeof(a)
的值是4。这是因为sizeof(array)
是整个数组的长度,而sizeof(a)
只是指针变量的长度,这也是显式传递数组长度的原因,因为指针本身并没有指定数组长度。