个性化阅读
专注于IT技术分析

如何在C++中打印数组参数的大小?

如何计算函数中数组参数的大小?

考虑下面的C++程序:

//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个字节的机器的。

main中的cout语句打印40,findSize中的cout打印8。原因是,数组总是在函数中传递指针,例如,findSize(int arr[])和findSize(int *arr)的意思完全相同。因此,findSize()中的cout语句打印一个指针的大小。详情请参阅这个和这个。

如何在函数中找到数组的大小?

我们可以传递”对数组的引用”。

//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++中的模板.

//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

我们也可以创建一个通用函数:

//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 40
80 80

现在, 下一步是打印动态分配的数组的大小。这是你的专人!我给你一个提示。

#include <iostream>
#include <cstdlib>
using namespace std;
  
int main()
{
     int *arr = ( int *) malloc ( sizeof ( float ) * 20);
     return 0;
}

本文贡献Swarupananda Dhua如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。

赞(0)
未经允许不得转载:srcmini » 如何在C++中打印数组参数的大小?

评论 抢沙发

评论前必须登录!