Returning Arrays/Pointers from a function

前端 未结 7 1325
醉梦人生
醉梦人生 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

    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.

提交回复
热议问题