How do pointer to pointers work in C?

2018-12-31 06:01发布

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

标签: c
14条回答
临风纵饮
2楼-- · 2018-12-31 06:52

You may want to read this : Pointers to Pointers

Hope this helps to clarify some basic doubts.

查看更多
只若初见
3楼-- · 2018-12-31 06:54

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<n; j++ )
        printf( "roll no = %d \n", i[j] );

    return 0;
}
查看更多
登录 后发表回答