How do pointer to pointers work in C?

前端 未结 14 1255
渐次进展
渐次进展 2020-11-22 02:03

How do pointers to pointers work in C? When would you use them?

14条回答
  •  长情又很酷
    2020-11-22 02:59

    How it works: It is a variable that can store another pointer.

    When would you use them : Many uses one of them is if your function wants to construct an array and return it to the caller.

    //returns the array of roll nos {11, 12} through paramater
    // return value is total number of  students
    int fun( int **i )
    {
        int *j;
        *i = (int*)malloc ( 2*sizeof(int) );
        **i = 11;  // e.g., newly allocated memory 0x2000 store 11
        j = *i;
        j++;
        *j = 12; ;  // e.g., newly allocated memory 0x2004 store 12
    
        return 2;
    }
    
    int main()
    {
        int *i;
        int n = fun( &i ); // hey I don't know how many students are in your class please send all of their roll numbers.
        for ( int j=0; j

提交回复
热议问题