21.6.  Arrays, Functions, and Return Values

[ fromfile: memoryaccess.xml id: arraysandfunctions ]

As in C, the declared return type of a function cannot be array (e.g., it cannot look like int[] or char[] or Point[]). Returning (addresses of) arrays from functions that are pointer-typed is allowed. However, this is not recommended in the public interface of a class.

You have seen that an array is a piece of unprotected memory. A class that encapsulates that memory should not have public member functions that return pointers to it. Doing so opens up the possibility for incorrect use of the memory by client code. A properly designed class completely encapsulates all interactions with any arrays used in the implementation of that class.

Arrays are never passed to functions by value; i.e., the array elements are not copied. If a function is called with an array in its argument list, for example,

   int a[] = {10, 11, 12, 13, 14, 15};
   void f(int a[]) {
      [ ... ]
   }
      [ ... ]
   f(a);
  

then the actual value passed is only a pointer to the first element in the array. Example 21.6 demonstrates this, by showing functions that pass and return arrays.

Example 21.6. src/arrays/returningpointers.cpp


#include <assert.h>

int paramSize;

void bar(int* integers) {
    integers[2]=3;                      1
}

int* foo(int arrayparameter[]) {
    using namespace std;
    paramSize = sizeof(arrayparameter);
    bar(arrayparameter);                2
    return arrayparameter;              3
}
    
int main(int argc, char** argv) {
    int intarray2[40] = {9,9,9,9,9,9,9,2,1};
    char chararray[20] = "Hello World"; 4
    int intarray1[20];                  5
    int* retval;                        6

//  intarray1 = foo(intarray2);         7

    retval = foo(intarray2);
    assert (retval[2] == 3);
    assert (retval[2] = intarray2[2]);
    assert (retval == intarray2);
    int refSize = getSize(intarray2);
    assert(refSize == paramSize);
    return 0;
}

1

Change the third element in the incoming array.

2

Pass an array by pointer to a function.

3

Return an array as a pointer from a function.

4

Special syntax for initializing char array.

5

Uninitialized memory.

6

Uninitialized pointer.

7

Error, intarray1 is like a char* const, it cannot be assigned to.