如何计算函数中数组参数的大小? 考虑下面的C++程序:
null
CPP
// A C++ program to show that it is wrong to // compute size of an array parameter in a function #include <iostream> using namespace std; void findSize( int arr[]) { cout << sizeof (arr) << endl; } int main() { int a[10]; cout << sizeof (a) << " " ; findSize(a); return 0; } |
输出:
40 8
上述输出适用于整数大小为4字节、指针大小为8字节的机器。 这个 库特 主打印件内的声明40,以及 库特 在findSize打印8中。原因是,数组总是在函数中传递指针,即findSize(int arr[])和findSize(int*arr)的意思完全相同。因此,findSize()中的cout语句打印指针的大小。看见 这 和 这 详细信息。 如何在函数中找到数组的大小? 我们可以传递一个“数组引用”。
CPP
// A C++ program to show that we can use reference to // find size of array #include <iostream> using namespace std; void findSize( int (&arr)[10]) { cout << sizeof (arr) << endl; } int main() { int a[10]; cout << sizeof (a) << " " ; findSize(a); return 0; } |
输出:
40 40
上面的程序看起来不太好,因为我们对数组参数的大小进行了硬编码。我们可以使用 C++中的模板 .
CPP
// A C++ program to show that we use template and // reference to find size of integer array parameter #include <iostream> using namespace std; template < size_t n> void findSize( int (&arr)[n]) { cout << sizeof ( int ) * n << endl; } int main() { int a[10]; cout << sizeof (a) << " " ; findSize(a); return 0; } |
输出:
40 40
我们还可以制作一个通用函数:
CPP
// A C++ program to show that we use template and // reference to find size of any type array parameter #include <iostream> using namespace std; template < typename T, size_t n> void findSize(T (&arr)[n]) { cout << sizeof (T) * n << endl; } int main() { int a[10]; cout << sizeof (a) << " " ; findSize(a); float f[20]; cout << sizeof (f) << " " ; findSize(f); return 0; } |
输出:
40 4080 80
现在,下一步是打印动态分配的数组的大小。是你的任务人!我给你一个暗示。
CPP
#include <iostream> #include <cstdlib> using namespace std; int main() { int *arr = ( int *) malloc ( sizeof ( int ) * 20); return 0; } |
本文由 斯瓦鲁帕南达杜瓦 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END