Passing Arrays To/From Functions

Array Parameters

Note

Only discussing one dimensional array in this document. Read the passing 2d array document as needed.

  • pass an array is the same as passing a pointer

  • only the first part (pointer part) is passed, data part stays

  • use [] syntax or * syntax

     1// ==== Array parameter ====
     2// ---- Correct ----
     3
     4// ignore the size
     5double average(double arr[], int size);
     6double average(double *arr, int size);
     7
     8// ---- Wrong ----
     9double average(double arr[size], int size);  // not compile
    10double average(double arr[3], int size);  // compile but 3 is ignored
    11
    12// ---- to call ----
    13double arr1[3] = {1.0, 2.0, 3.0};
    14cout << average(arr1, 3) << endl;
    15// cout << average(arr1[], 3) << endl;  // wrong!
    

Return an Array

  • Returning an array is the same as returning a pointer

  • Only the first part (pointer part) is passed to outside, data part stays

  • The return type should use pointer syntax

  • Never return a local array from a function

     1// ==== Array as returned value ====
     2
     3// ---- Correct ----
     4// return a dynamic array
     5int *makeSequence(int size) {
     6  int *sequence;
     7  sequence = new int[size];
     8  for (int i = 0; i < size; ++i)
     9    sequence[i] = i + 1;
    10  return sequence;
    11}
    12
    13// ---- Wrong ----
    14int *makeSequence(int size) {
    15  int sequence[size];
    16  for (int i = 0; i < size; ++i)
    17    sequence[i] = i + 1;
    18  return sequence;
    19}
    20
    21// ---- to call ----
    22int *seq = makeSequence(10);
    23delete [] seq;
    
  • Read the returning multidimensional arrays document as needed