Thread: returning array

  1. #1
    Registered User
    Join Date
    Feb 2004

    returning array

    It is possible to return a array from a function to main?

  2. #2
    Registered User Xzyx987X's Avatar
    Join Date
    Sep 2003
    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:

    //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;
    This kind of stuff involves some fancy tricks with pointers an memory allocation so if there's anything you don't understand let me know

  3. #3
    Registered User
    Join Date
    Feb 2004
    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?

  4. #4
    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.

  5. #5
    Registered User
    Join Date
    Mar 2004
    Alternatively return an std::vector.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Parsing and returning array pointers?
    By thealmightyone in forum C Programming
    Replies: 26
    Last Post: 03-26-2009, 03:38 PM
  2. Returning an Array
    By mmarab in forum C Programming
    Replies: 10
    Last Post: 07-19-2007, 07:05 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Replies: 6
    Last Post: 10-21-2003, 09:57 PM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM