Lesson 98 +10 XP

Passing Arrays to Functions

Passing Arrays to Functions

Functions and arrays are a common team: you pass the array to a function and let it work on all elements.

Arrays decay to pointers

When you pass an array, it decays to a pointer to its first element. These two parameter declarations are equivalent:

void showArray(int myNumbers[5]) { }   // same as...
void showArray(int* myNumbers) { }     // ...this

Inside the function you receive the address of the first element, not the array's size. That's why you usually pass the size in as another parameter:

void printArray(int theArray[], int size) {
  for (int i = 0; i < size; i++) {
    cout << theArray[i] << endl;
  }
}

Call and loop

Build an array, call the function with the array and its size, and its loop prints each element:

int main() {
  int myNumbers[5] = {10, 20, 30, 40, 50};
  printArray(myNumbers, 5);   // prints 10 20 30 40 50
  return 0;
}

Watch the size

The function can't tell how big an array is by itself. Use the passed-in size to bound the loop, or you may read past the end of the array.

Modifications reach the caller

Because the array is passed as a pointer, writing to theArray[i] inside the function changes the original array back in main.

TL;DR

  • An array passed to a function decays to a pointer to its first element.
  • int my[] and int* my are equivalent as parameters.
  • The pointer doesn't carry the size, so pass the size too.
  • Loop up to size to stay inside the array.
  • The function sees and can modify the original elements.