C + + must be aware of (vi) array parameters

Source: Internet
Author: User

Notes:

C + + There is no such thing as an "array parameter", which, when passed in, essentially passes only a pointer to its first element.

void average( int array[12] ); // 形参是一个int *
void average( int array[] ); // 形参仍然是一个int *
void average( int (&array)[12] ); // 现在函数只能接受大小为12的整型数组
// 注意:不可以使用int *初始化 int(&)[n]

template< int n >
void average( int (&array)[n]); // 借助模板使代码泛化

void average_n(int array[], int nSize); // 传统做法是把数组大小明确传入函数

template< int n >
inline void average( int (&array)[n] ) // 模板与传统做法结合实现
{
average_n(array, n);
}

In the case of multidimensional arrays, the following declaration statements are equal, but the second boundary (and subsequent) of the array is not degraded:

void process( int array[10][20] ); // 形参是指向数组首元素的指针
void process( int (*array)[20] ); // 形参是指向一个具有20个元素的数组的指针
void process( int array[][20] ); // 形参是指针,但是比前边两个语句更加清晰

Similarly, with templates and traditional practices, you can implement array parameter input without explicit incoming size:

void process_2d(int *arr, int n, int m);

template< int n, int m >
inline void process( int (&array)[n] )
{
process_2d(array, n, m);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.