[ 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; } int* foo(int arrayparameter[]) { using namespace std; paramSize = sizeof(arrayparameter); bar(arrayparameter); return arrayparameter; } int main(int argc, char** argv) { int intarray2[40] = {9,9,9,9,9,9,9,2,1}; char chararray[20] = "Hello World"; int intarray1[20]; int* retval; // intarray1 = foo(intarray2); retval = foo(intarray2); assert (retval[2] == 3); assert (retval[2] = intarray2[2]); assert (retval == intarray2); int refSize = getSize(intarray2); assert(refSize == paramSize); return 0; }
<include src="src/arrays/returningpointers.cpp" href="src/arrays/returningpointers.cpp" id="returningpointerscpp" mode="cpp"/>
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |