Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Arrays/Pointers from a function

I am trying to create a new integer array which is derived from a string of characters. For example :

char x[] = "12334 23845 32084";  

int y[] = { 12334, 23845, 32084 };

I am having trouble understanding how to return an array ( which I understand isn't possible ) from a function.

I originally tried :

/* Convert string of integers into int array. */
int * splitString( char string[], int n )
{
    int newArray[n];

    // CODE

    return ( newArray );
}

int main( void )
{
    int x[n] = splitString( string, n );

    return ( 0 );
}

I later learned that you can not do this.

How do pointers work in regards to functions?

Thank you.

like image 917
Garee Avatar asked Mar 21 '11 14:03

Garee


People also ask

How do I return a pointer array from a function?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

Can a function return an array?

Although functions cannot return arrays, arrays can be wrapped in structs and the function can return the struct thereby carrying the array with it.

Is it possible to return of pointer from a function?

We can pass pointers to the function as well as return pointer from a function. But it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns.


2 Answers

Typically, you require the caller to pass in the result array.

void splitString( const char string[], int result[], int n) {
    //....
}

This is advantageous because the caller can allocate that memory wherever they want.

like image 128
Puppy Avatar answered Oct 14 '22 00:10

Puppy


The problem is you're returning a pointer to something on the stack. You need to create your array on the heap, then free it when you're done:

int * splitString( char string[], int n )
{
    int *newArray = malloc(sizeof(int) * n);

    // CODE

    return ( newArray );
}

int main( void )
{
    int *x = splitString( string, n );

    // use it

    free(x);

    return ( 0 );
}
like image 32
Brian Roach Avatar answered Oct 13 '22 22:10

Brian Roach