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.