Returning Arrays/Pointers from a function

前端 未结 7 1318
醉梦人生
醉梦人生 2020-11-28 12:07

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,         


        
7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 12:38

    The main issue i see is trying to return memory which you allocated on the stack, which becomes invalid once the function it was allocated in reutrns (in this case your splitString). What you can do is allocate the memory in the caller, and pass a pointer to the beginning of the array into the function

    /* Convert string of integers into int array. */
    void splitString(char string[], int *out_arr, int n )
    {
    
        // code that fills each cell of out_arr
    
    }
    
    int main( void )
    {
        int x[n];
        splitString( string,(int *)x, n );
    
        return ( 0 );
    }
    

提交回复
热议问题