Arrays, Functions, and Return Values
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 to) arrays from functions that are pointer-typed is allowed. However, this is not recommended in the public interface of a class.
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 valuethe array elements will not be copied. If a function is called with an array in its argument list, for example,
int a[] = {10, 11, 12, 13, 14, 15}; [ ... ] f(a[]); [ ... ]
then the array expression is interpreted as a pointer to the first element in the array.
Example 22.5. src/arrays/returningpointers.cpp
#include 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)Errorintarray1 is like a // char* const. It cannot be assigned to. |