在C++中将数组作为参数传递

Passing array as arguments in C++

本文关键字:参数传递 数组 C++      更新时间:2023-10-16

我尝试在C++中传递C++数组作为参数,但遇到了一些问题。我经历了这些,但还是没能解决问题。

C++
#include<iostream>
using namespace std;
void comb(int a[])
{
    int alen = sizeof(a)/sizeof(*a);
    cout << alen << endl;
    /* Since 'I' know the size of a[] */
    for(int i = 0; i < 7; i++)
    cout << a[i] << " ";
    cout << endl;
}
int main()
{ 
    int a[] = {1,2,3,4,5,6,7};
    comb(a);
}
Output
2
1 2 3 4 5 6 7

我的问题是,为什么数组的大小被计算为2?

当您将数组指定为函数参数时,它会降级为指针。因此,sizeof(a)是指针的大小,而不是数组的(字节)大小。您需要将长度作为单独的参数传入,或者使用类似std::vector的参数。

C不将数组的长度存储在内存中,因此被调用的函数没有办法知道阵列有多长。

sizeof是在编译时计算的,除非将其应用于数组文字,否则将无法获得数组的长度。

您可能需要考虑通过引用传递std::vector<int>