数组....在C / C ++的大小? [英] Size of an Array.... in C/C++?

查看:146
本文介绍了数组....在C / C ++的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,你已经和数组A [] ...传递给你一些功能与下面的函数原型说:

 无效美孚(INT A []);

好吧,因为你知道这是一种很难找到数组的大小不知道某种结局变量或明知规模已经是...

那么这里是这笔交易虽然。我似乎有些人搞清楚一个挑战问题,我不明白他们是怎么做到的。我没能看到,当然他们的来源$ C ​​$ C,这就是为什么我在这里问。

有谁知道这将是多么甚至可以远程可能找到数组的大小?或许真的像什么免费的()函数在C 22

你觉得这??

 模板< typename的E,INT大小和GT;
INT ArrLength(E(安培)[尺寸]){返回大小;}无效的主要()
{
    INT ARR [17];
    INT sizeofArray = ArrLength(ARR);
}


解决方案

这是函数的签名是不是采取一个数组的函数,而是一个的指针 INT 。则无法获得该函数内的阵列的大小,并且将必须把它作为一个额外的参数的函数。

如果您被允许更改功能的签名有不同的选择:

C / C ++(简单):

 无效F(INT *数据,诠释大小); //功能
F(数组,数组的sizeof / sizeof的数组[0]); //调用者code

C ++

 模板< INT N'GT;
空隙F(INT(安培;阵列)[N]); //内楼大小N嵌入型
F(数组); //调用者code

C ++(虽然派遣):

 模板< INT N'GT;
空隙F(INT(安培;阵列)[N]){//分派
   F(阵列,N);
}
无效F(INT *数组,INT大小); //实际功能,按选项1
F(数组); //编译器处理类型为每2

Okay so you have and array A[]... that is passed to you in some function say with the following function prototype:

void foo(int A[]);

Okay, as you know it's kind of hard to find the size of that array without knowing some sort of ending variable or knowing the size already...

Well here is the deal though. I have seem some people figure it out on a challenge problem, and I don't understand how they did it. I wasn't able to see their source code of course, that is why I am here asking.

Does anyone know how it would even be remotely possible to find the size of that array?? Maybe something like what the free() function does in C??

What do you think of this??

template<typename E, int size>
int ArrLength(E(&)[size]){return size;}

void main()
{
    int arr[17];
    int sizeofArray = ArrLength(arr);
}

解决方案

The signature of that function is not that of a function taking an array, but rather a pointer to int. You cannot obtain the size of the array within the function, and will have to pass it as an extra argument to the function.

If you are allowed to change the signature of the function there are different alternatives:

C/C++ (simple):

void f( int *data, int size );             // function
f( array, sizeof array/sizeof array[0] );  // caller code

C++:

template <int N>
void f( int (&array)[N] );                 // Inside f, size N embedded in type
f( array );                                // caller code

C++ (though a dispatch):

template <int N>
void f( int (&array)[N] ) {                // Dispatcher
   f( array, N );
}
void f( int *array, int size );            // Actual function, as per option 1
f( array );                                // Compiler processes the type as per 2

这篇关于数组....在C / C ++的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆