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.
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.
Although functions cannot return arrays, arrays can be wrapped in structs and the function can return the struct thereby carrying the array with it.
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.
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.
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With