参数传递(array)
As with any other type, we can define an array parameter as a reference or nonreference type. Most commonly, arrays are passed as plain, nonreference types, which are quietly converted to pointers.
As with any type, we can define an array parameter as a reference to the array. If the parameter is a reference to the array, then the compiler does not convert an array argument into a pointer. Instead, a reference to the array itself is passed. In this case, the array size is part of the parameter and argument types. The compiler will check that the size of the array argument matches the size of the parameter:
// ok: parameter is a reference to an array; size of array is fixed void printValues(int (&arr)[10]) { /* ... */ } int main() { int i = 0, j[2] = {0, 1}; int k[10] = {0,1,2,3,4,5,6,7,8,9}; printValues(&i); // error: argument is not an array of 10 ints printValues(j); // error: argument is not an array of 10 ints printValues(k); // ok: argument is an array of 10 ints return 0; }
As with any array, a multidimensioned array is passed as a pointer to its zeroth element. An element in a multidimenioned array is an array. The size of the second (and any subsequent dimensions) is part of the element type and must be specified:
// first parameter is an array whose elements are arrays of 10 ints void printValues(int (matrix*)[10]);
We could also declare a multidimensioned array using array syntax. As with a single-dimensioned array, the compiler ignores the first dimension and so it is best not to include it:
// first parameter is an array whose elements are arrays of 10 ints void printValues(int matrix[][10]);
There are three common programming techniques to ensure that a function stays within the bounds of its array argument(s)
1、The first places a marker in the array itself that can be used to detect the end of the array. C-style character strings are an example of this approach.
2、Using the Standard Library Conventions
A second approach is to pass pointers to the first and one past the last element in the array. This style of programming is inspired by techniques used in the standard library.
void printValues(const int *beg, const int *end) { while (beg != end) { cout << *beg++ << endl; } } int main() { int j[2] = {0, 1}; // ok: j is converted to pointer to 0th element in j // j + 2 refers one past the end of j printValues(j, j + 2); return 0; }
3、Explicitly Passing a Size Parameter
浙公网安备 33010602011771号