|
Since an array is a pointer, arrays are passed to functions by pointer. Here is a function that sets the first n variables of array of integers A to 0.
void zero(int* A, int n) { for(int k = 0; k < n; k++) { A[k] = 0; } }
To use zero, pass it an array and the size of that array. Assume that constant Bsize has previously been defined.
int B[Bsize];
zero(B, Bsize);
Notice that argument B does not have
any decoration. Don't add [] after it.
Nothing needs to be done to convert
B to a pointer; it already is a pointer.
C++ offers an alternative notation for passing arrays to functions that we have already seen. Instead of writing int* A in the function heading, you can write int A[]. Heading
void zero(int A[], int n)is equivalent to heading
void zero(int* A, int n)The former form has the advantage that it clearly indicates that A is an array, not a pointer to just one thing. For that reason, it is preferred. Note that Java notation int[] A is not allowed in C++. The brackets come after the name of the parameter.
|