When the C ++ array is used as a function parameter, the array size method is passed. The Function Array

Source: Internet
Author: User

When the C ++ array is used as a function parameter, the array size method is passed. The Function Array

If you don't talk much about it, let's demonstrate the error first:

Void fun (int arr [arr_num]) {

//...

}

 

Int main (){

//...

Int * arr = new int [10];

Fun (arr)

//...

Return 0;

}

Many users want to transfer the array size to the function to facilitate operations. Although the above method looks pleasing to the eye, it is wrong and arr_num does not play any role, that is to say, no matter how big the array you pass in is, no error is reported.

The correct method is as follows:

Method 1:

Pass the array size as another parameter

Void fun (int * arr, int arr_num ){

//...

}

Method 2:

Void fun (int (& arr) [arr_num]) {

//...

}

It has been tested that this method also has the following error:

1. When the passed parameter is not a pointer, this method is correct, that is:

Int arr [10] = {0 };

Fun (arr );

2. When the passed parameter is a pointer, this method returns an error, namely:

Int * arr = new int [10];

Fun (arr );

 

To sum up, the first method is relatively secure, and it is no big deal to add another parameter.

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.