C++数组作为形参传递给函数

以下三种形式等价

void function(const int *arg);
void function(const int arg[]);
void function(const int arg[10]);//这里维度表示期望有10个,并不代表真实为10个

以上三个函数等价于将数组的头指针const int*类型传递给函数,但是不知道数组的长度。有以下方法解决。
1.使用标记指定数组长度
使用一个确定的标记告诉当读取到该标记时,表示数组结束。
2.使用标准库

int a[] = {1,2,3,4,5};
void function(const int *begin, const int *end){
    for(auto i = begin;i!=end;++i){
        cout<<*i<<endl;
    }
function(begin(a),end(a));

begin()函数返回数组a的第一个元素的地址,end()函数返回数组a最后一个元素的下一个地址。
3.显示的传递一个表示数组大小的形参

void function(const int a[], size_t size);

猜你喜欢

转载自blog.csdn.net/weixin_37895339/article/details/79573466