It is possible to return a array from a function to main?
This is a discussion on returning array within the Windows Programming forums, part of the Platform Specific Boards category; It is possible to return a array from a function to main?...
It is possible to return a array from a function to main?
First, this should be in either in the C or C++ forum, not Windows. And yes there is a way to do it, here's how:
This kind of stuff involves some fancy tricks with pointers an memory allocation so if there's anything you don't understand let me knowCode://Program that returns an array of intigers #include <stdio.h> #include <stdlib.h> int * GetArray( int intA, int intB, int intC ); int main(void) { int * arrayPtr; arrayPtr = GetArray( 1, 2, 3 ); printf( "%d %d %d\n", arrayPtr[0], arrayPtr[1], arrayPtr[2] ); free( (void *) arrayPtr ); //Free dynamically allocated memory once you finish with it to avoid memory leaks system( "PAUSE" ); return 0; } int * GetArray( int intA, int intB, int intC ) { int * arrayPtr = (int *) malloc( sizeof( int ) * 3 ); //If you allocate the array withing the funtion malloc must be used or the the array be deallocated when the function exits arrayPtr[0] = intA; arrayPtr[1] = intB; arrayPtr[2] = intC; return arrayPtr; }
Sorry, posted at the wrong place.
So this is using a pointer to point to a array in the function then pass the pointer back to the main?
Just think of array[] as *array. Like was sown above, to return an array just set the return type as TYPE * ... The same goes for passing values.
Alternatively return an std::vector.