/* Example of passing arrays to functions. John Sterling CS1124 Polytechnic University */ #include // cout, endl using namespace std; void display(const int x[], int size); void display2d(const int x[][3], int size); int main() { int arr[] = {2, 3, 5, 8, 13}; int arr2[] = {2, 4, 8, 16, 32, 64, 128}; int arr2d[][3] = {{2, 4, 8}, {3, 9, 27}}; // A 2d array is just an array of arrays. // To pass an array to a function, just give the name of the array. // The array's name is really just the "address" (or location) of // the whole array. The array, itself, is NOT being copied, // only the address of the array. Even though this looks like pass-by-value, // we are NOT making a copy of the array and any changes that the function // makes to the array WILL actually change the array that was passed in. display(arr, 5); display(arr2, 7); // Even if the array has more than one dimension we can pass the whole // array just by giving the array's name. Again, what we're really passing // is just the address (or location) of the array. display2d(arr2d, 2); } // This function displays an array. There is no way in C++ for the function to // know how big the array is just by looking at it, so we also have to pass // the size of the array. void display(const int x[], int size) { for (int i = 0; i < size; i++) cout << x[i] << " "; cout << endl; } // This functoin is passed a two dimensional array to print. // It does so by passing each array to the function that displays // one-dimensional arrays. void display2d(const int x[][3], int size) { for (int i = 0; i < size; i++) display(x[i], 3); }