数组作为函数参数

数组作为函数参数几种形式对比:

 

#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; 在函数外部则正常;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值