wuc*_*ang 0 c++ arrays parameters integer
我的代码很简单:
#include <iostream>
using namespace std;
int test(int b[]){
cout<<sizeof(b)<<endl;
return 1;
}
int main(){
int a[] ={1,2,3};
cout<<sizeof(a)<<endl;
test(a);
system("pause");
}
Run Code Online (Sandbox Code Playgroud)
此代码的输出是:
12
4
Run Code Online (Sandbox Code Playgroud)
这意味着当一个[]作为参数转移到函数test()时,已经被恶化为int*,所以大小(b)的输出是4,而不是12.所以我的问题是,怎么能我在函数test()里面得到b []的实际长度?
您可以使用功能模板执行此操作:
#include <cstddef> // for std::size_t
template<class T, std::size_t N>
constexpr std::size_t size(T (&)[N])
{
return N;
}
Run Code Online (Sandbox Code Playgroud)
然后
#include <iostream>
int main()
{
int a[] ={1,2,3};
std::cout << size(a) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
请注意,在C和C++中,int test(int b[])是另一种说法int test(int* b),因此test函数内部没有数组大小信息.此外,您可以使用知道其大小的标准库容器类型,例如std::array.
| 归档时间: |
|
| 查看次数: |
46 次 |
| 最近记录: |