23E. Returning an Array from a Function

Since an array is a pointer, a function that returns an array must return a pointer. For example, the following function returns a new array A of real numbers of size n, where A[i] = i for i = 0, …, n − 1.

  double* countArray(const int n)
  {
    double* A = new double[n];
    for(int i = 0; i < n; i++)
    {
      A[i] = (double) i;
    }
    return A;
  }

Be careful with arrays that are in the run-time stack. Consider the following attempt to allocate an array of integers.

  int* allocArr(int n)
  {
    int A[n];
    return A;
  }
The compiler will not give you an error on this. A is an array of integers (type int*), so the correct type of thing is returned. But the returned pointer is pointing into the frame of allocArr. As soon as allocArr returns, that becomes a dangling pointer. To allocate a chunk that you need to keep using after the function that creates the chunk returns, use new.


Exercises

  1. Write a function copyArray(A, n) that returns a copy of the first n members of array A (as a new array). Assume that A is an array of doubles. Answer