Why use double indirection? or Why use pointers to pointers?

前端 未结 18 2265
失恋的感觉
失恋的感觉 2020-11-22 10:37

When should a double indirection be used in C? Can anyone explain with a example?

What I know is that a double indirection is a pointer to a pointer. Why would I ne

18条回答
  •  爱一瞬间的悲伤
    2020-11-22 11:26

    Adding to Asha's response, if you use single pointer to the example bellow (e.g. alloc1() ) you will lose the reference to the memory allocated inside the function.

    void alloc2(int** p) {
       *p = (int*)malloc(sizeof(int));
       **p = 10;
    }
    
    void alloc1(int* p) {
       p = (int*)malloc(sizeof(int));
       *p = 10;
    }
    
    int main(){
       int *p = NULL;
       alloc1(p);
       //printf("%d ",*p);//undefined
       alloc2(&p);
       printf("%d ",*p);//will print 10
       free(p);
       return 0;
    }
    

    The reason it occurs like this is that in alloc1 the pointer is passed in by value. So, when it is reassigned to the result of the malloc call inside of alloc1, the change does not pertain to code in a different scope.

提交回复
热议问题