在C++中将数组作为参数传递
Passing array as arguments in C++
我尝试在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>
。
相关文章:
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 如何在模板函数中实例化其长度使用模板参数的数组
- 基于参数创建数组
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组
- 在 c++ 中使用模板传递数组时出现问题
- Pybind11 默认参数 numpy 数组或 None
- 传递数组结构、ofstream 和 interger 以运行
- 有没有办法根据命令行参数定义数组大小?运行时与编译时实例化?
- 在C++中传递数组作为函数参数的方法
- 函数参数绑定通过参考与传递指针传递数组的规则
- 如果数组变量在 c# 代码中定义为“ref”参数,则如何传递数组变量
- 你究竟如何通过函数的参数传递数组?
- c++ 传递数组而不是可变长度参数列表
- 如何在我的实际参数中通过引用传递数组
- 如何在函数C++中传递数组成员作为参数
- 在函数中传递数组作为引用参数
- 通过引用传递数组参数
- 在c++中传递数组作为函数参数
- 如何在构造函数中传递数组作为参数?c++
- 为什么编译器不在参数中传递数组字符 *arr[] 的大小?