Passing Arrays
/* * Demonstrate some pecularities of array passing in C. */ #include <iostream> using namespace std; // Each version receives the same size-5 integer array from the main pgm. // Receive it as declared in main. void rcvA(int arr[5]) { cout << "rcvA: "; for(int m = 0; m < 5; m++) cout << arr[m] << " "; cout << endl; } // Receive it as the system sends it -- a pointer to the first item in the // array. void rcvB(int *arr) { cout << "rcvB: "; for(int m = 0; m < 5; m++) cout << arr[m] << " "; cout << endl; } // Since it sends a pointer and ignores the array size anyway, the system // lets you leave it out here, too. void rcvC(int arr[]) { cout << "rcvC: "; for(int m = 0; m < 5; m++) cout << arr[m] << " "; cout << endl; } // In fact, so long as the system is going to ignore the size anyway, we can // write what we want. The 1024 doesn't make the array that large, // however; it's however large its creator made it. rcvD can't find out. void rcvD(int arr[1024]) { cout << "rcvD: "; for(int m = 0; m < 5; m++) cout << arr[m] << " "; cout << endl; } int main() { // Here's the array all the fuss is about. int arr[5]; // Put some stuff there. for(int i = 0; i < 5; ++i) arr[i] = 2*i -3; // Do exactly what the functions do. cout << "main: "; for(int m = 0; m < 5; m++) cout << arr[m] << " "; cout << endl; // Now run the functions. rcvA(arr); rcvB(arr); rcvC(arr); rcvD(arr); }

When passing an array, C++ doesn't. It actually passes the pointer to the first position (subscript zero). So:

  1. In the called function, you cannot ask the array how big it is, since it's not an array. The iterator doesn't know how big the array is any more than a subscript would. (It is a common idiom in C and C++ that, when sending an array, an additional parameter is used to send its size also.)
  2. You may declare the parameter that receives the array as an array or as a pointer of the appropriate type.
  3. If declare the parameter as an array, the size is meaningless, so you may omit it and just use empty brackets. If you do give a size, it is meaningless, and ignored. Generally, it's probably better not to give a size, since it can be misleading.

Arrays in C are not considered one of the language's design glories.