// How to return an array from a function // returning arrays can be confusing because you need to // return a reference and copy the results into a new memory location // since an array allocated on the stack, like the example below, doesn't // disappear when the routine ends. // filename: arrayreturndemo.cpp written by Lee Devlin 4-6-2011 #include using namespace std; char* retArray(char []); // the name of the returned variable is optional in the prototype; int main() { char arr1[]="first"; char freespace[20]; // set up some free space holding an empty char array int n; char * arr4; // set up pointer to char array arr4 = freespace; // assign pointer to location of freespace cout << arr4 << endl; // see what garbage is in freespace (caution this could hang program!) cout << &arr4 << endl; // check location of arr4 pointer strcpy(arr4, retArray(arr1)); cout << "Arr4 contains " << arr4 << endl; system("pause"); } char* retArray(char arr0[]) // this simple function appends the string 'last' to the incoming arrary { char arr3[20]; strcpy(arr3, arr0); strcat(arr3, " last"); cout << "Arr3 contains " << arr3 << endl; return arr3; }