代码改变世界

C++在函数中求数组大小

2012-06-12 22:02  youxin  阅读(937)  评论(0编辑  收藏  举报

 在函数参数中数组已经退化为指针。

int size(int a[] )

{

   return sizeof(a)/sizeof(*a); 输出恒为1

  }

可以利用函数模板,看下面一个简单例子:

 

#include <iostream>

template <typename T, ::size_t N>
void f (T (&) [N])
{
 std::cout << N << std::endl;
}

struct test { };

int main ()
{
 int i [5];
 double d [10];
 test t [20];

 f(i);
 f(d);
 f(t);

 return 0;
}

会输出:5  10 20

深入:

http://blog.chinaunix.net/uid-790245-id-2037333.html  

http://hi.baidu.com/xemoaya/item/806b6409152ca330a2332ae1