pointer of a pointer in linked list append

后端 未结 7 1851
Happy的楠姐
Happy的楠姐 2020-11-30 09:49

I normally program in python. To increase performance of my simulations, I am learning C. I have a problem to understand the use of a pointer of a pointer when implementing

7条回答
  •  感动是毒
    2020-11-30 10:08

    You need to do it that way for the function to be able to allocate the memory. Simplifying the code:

    main()
    {
      void *p;
      p = NULL;
      funcA(&p);
    
      int i;
      i = 0;
      funcB(&i);
    }
    
    funcA(void **q)
    {
      *q = malloc(sizeof(void*)*10);
    }
    
    funcB(int *j)
    {
      *j = 1;
    }
    

    This code is done that way so the subfunction funcA can allocate the p pointer. First of all, consider void* p as if it where int i. What you do by doing p = NULL is similar in a way as int i = 0. Now if you pass &i you do not pass the address of 0, you pass the address of i. Same thing happens with &p you pass the address of the pointer.

    Now in funcA, you want to make the allocation, so you use malloc but if you would do q = malloc(... and q would have been void* q in the main function p would not have been allocated. Why? Think of funcB, j holds the address of i, if you want to modify i you would then do *j = 1, because if you would do j = 1 then you would have made j point to another memory region instead of i. It is the same with q for funcA. think of it as * q it is a pointer to the type of p which is void*, but in case of funcB it is a int. Now you want to modify the address p is pointing at, it means that you do not want to modify the address q is pointing at, you want to modify the pointing address at what q is pointing at, aka *q or p.

    If it isn't yet clear. Try to think of boxes. I have drawn a quick example with funcA of the boxes involved. Each box has a name (within the box), this box is in the virtual memory of the process at an arbitrary address, and each box contain a value. In this view we are in the state where the funcA(&p) has been called and the malloc will be done.

    enter image description here

提交回复
热议问题