Tuesday, July 28, 2009

C++ return an array?

i need to do that

C++ return an array?
//make a function that returns the array





char* arrayReturn( )


{


static char this[20] = "Hello World";


return(this);


}





//Then call the function


main()


{


char *hello;


hello = arrayReturn( );


printf(hello);


}
Reply:I agree with ninesunz, but there are some caveats with the technique.





If you return an array that is defined as a local variable in your called function, that variable will need to be static (as ninesunz demonstrated) or else it will be removed from the stack when the called function exits. Another way would be to pass an array as a parameter of the function and use that:





void arrayReturn(char * returnArray)


{


strcpy(returnArray, "Hello, world");


}





Note that returnArray will need to be large enough to hold the result, or pass another parameter to specify the size of the array, or allocate the space for the array in the called function on the heap using the "new" operator.





Look into using std::vector though, instead.
Reply:Actually in C++ you cannot return an array directly but you need to use some tricky ways as follow:





(1) Create a link list and return the head pointer of the link list to the calling fucntion. You cannot simply return pointer to an array for two reasons: first if the array is local that function then the pointer returned to the calling function points to the memory address which is no longer valid and second and most important reason is when you return a pointer to the calling function you only knows the starting point of the array but not the end point. Means if you use ++ operator on the returned pointer you don't know where to stop incrementing the pointer as don't know the size of the array.





(2) Create a class which contains the array of the type you want to return and instead of returning the array return the object of this class which contains the array you want. For example suppose you want to return an array of Integer then create class as following:





class ArrayOfInteger


{


private int myint[10];


public ArrayOfInteger(int myint[])


{


this.myint=myint;


}


make a getter of myint as well.


}








Solution:





In called function:


return new ArrayOfInteger(%26lt;arrayofint you want to return%26gt;);





In calling function:


int callingMyInt = calledFunction.getMyInt();


No comments:

Post a Comment