Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to do it that way for the function to be able to allocate the memory. Simplifying the code:</p> <pre><code>main() { void *p; p = NULL; funcA(&amp;p); int i; i = 0; funcB(&amp;i); } funcA(void **q) { *q = malloc(sizeof(void*)*10); } funcB(int *j) { *j = 1; } </code></pre> <p>This code is done that way so the subfunction <code>funcA</code> can allocate the <code>p</code> pointer. First of all, consider <code>void* p</code> as if it where <code>int i</code>. What you do by doing <code>p = NULL</code> is similar in a way as <code>int i = 0</code>. Now if you pass <code>&amp;i</code> you do not pass the address of <code>0</code>, you pass the address of <code>i</code>. Same thing happens with <code>&amp;p</code> you pass the address of the pointer.</p> <p>Now in funcA, you want to make the allocation, so you use <code>malloc</code> but if you would do <code>q = malloc(...</code> and q would have been <code>void* q</code> in the main function p would not have been allocated. Why? Think of <code>funcB</code>, j holds the address of i, if you want to modify i you would then do <code>*j = 1</code>, because if you would do <code>j = 1</code> 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 <code>&lt;type of p&gt;* q</code> 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 <code>*q</code> or <code>p</code>.</p> <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 <code>funcA(&amp;p)</code> has been called and the malloc will be done.</p> <p><img src="https://i.stack.imgur.com/ek6Tl.png" alt="enter image description here"></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload