数组作为函数参数几种形式对比:
#include <iostream>
using namespace std;
void test_array(float* joint_arr )
{
cout<< "------------function inner------------" <<endl;
cout<< sizeof(joint_arr) <<endl;
cout<< sizeof(joint_arr[1]) <<endl;
cout<< sizeof(joint_arr)/sizeof(joint_arr[0]) <<endl;
for(int i=0;i<5;i++)
{
cout<< joint_arr[i] <<endl;
}
}
void test_array_1(float joint_arr[5] )
{
cout<< "------------function inner------------" <<endl;
cout<< sizeof(joint_arr) <<endl;
cout<< sizeof(joint_arr[1]) <<endl;
cout<< sizeof(joint_arr)/sizeof(joint_arr[0]) <<endl;
for(int i=0;i<5;i++)
{
cout<< joint_arr[i] <<endl;
}
}
int main()
{
float joint_arr [5]={1,2,3,4,5};
test_array(joint_arr);
cout<< "------------function outer------------" <<endl;
cout<< sizeof(joint_arr) <<endl;
cout<< sizeof(joint_arr[1]) <<endl;
cout<< sizeof(joint_arr)/sizeof(joint_arr[0]) <<endl;
system("pause");
return 0;
}
输出:
------------function inner------------
8
4
2
1
2
3
4
5
------------function outer------------
20
4
5
只要函数体一样,这几种是等价的:
void test_array_1(float joint_arr[5] );
void test_array_2(float joint_arr[] );
void test_array_3(float* joint_arr );
数组作为函数参数时,传入的其实只是指针,数组大小相关信息并未传入;在函数内部数组名joint_arr,等价于float *,用sizeof()求其所占字节数等于sizeof(float*),而不是sizeof(float)*5; 在函数外部则正常;