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.
Solution 1:
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.
Solution 2:
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 );
}
Solution 3:
int * splitString( char string[], int n )
{
int newArray[n];
return ( newArray );
}
This is very bad! The array newArray
local to the function gets destroyed when the function returns. You'd be left out with a dangling pointer and using it would invoke undefined behaviour.
You can't return an array from a function. The best you can do is
int * splitString( char string[], int n )
{
int *newArray = malloc(n*sizeof(int)); // the array gets allocated on the heap rather than on the stack(1)
// Code
return ( newArray );
}
Don't forget to free the allocated memory.
(1) Note that the standard doesn't use/define the term stack or heap as such.
Solution 4:
Rather than returning an array with return (newArray)
, you return a pointer to the first element of newArray.
The problem is that you're allocating the array the wrong way. If you instantiate it with int newArray[n]
, memory gets allocated on the current stack frame. That memory will be freed as soon as your function returns, and whatever was in the array will be garbage. Instead, do the following:
int *newArray = malloc(n * sizeof(int));
// etc.
return newArray
By using malloc
, you allocate memory on the heap, where it will survive past the end of the current stack frame. Just remember to free(newArray)
somewhere in your program when you're done.
Solution 5:
You can wrap an array in a structure and then return an instance of the structure. I'm mentioning this for completeness, it's not really something you'd want to do as it's ugly and there are better alternatives.
#include <stdio.h>
struct retval
{
int a[10];
};
struct retval test()
{
struct retval v = {{1, 5, 6}};
return v;
}
int main()
{
struct retval data = test();
printf("%d %d\n", data.a[1], data.a[2]);
}