Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You want to use a pointer-to-pointer:</p> <pre><code>void someFunction (int **data) { *data = malloc (sizeof (int)); } void useData (int *data) { printf ("%p", data); } int main () { int *data = NULL; someFunction (&amp;data); useData (data); return 0; } </code></pre> <p>Why? Well, you want to change your pointer <code>data</code> in the main function. In C, if you want to change something that's passed in as a parameter (and have that change show up in the caller's version), you have to pass in a pointer to whatever you want to change. In this case, that "something you want to change" is a pointer -- so to be able to change that pointer, you have to use a pointer-to-pointer...</p> <p>Note that on top of your main problem, there was another bug in the code: <code>sizeof(data)</code> gives you the number of bytes required to store the pointer (4 bytes on a 32-bit OS or 8 bytes on a 64-bit OS), whereas you really want the number of bytes required to store <em>what the pointer points to</em> (an <code>int</code>, i.e. 4 bytes on most OSes). Because typically <code>sizeof(int *)&gt;=sizeof(int)</code>, this probably wouldn't have caused a problem, but it's something to be aware of. I've corrected this in the code above.</p> <p>Here are some useful questions on pointers-to-pointers:</p> <p><a href="https://stackoverflow.com/questions/897366/how-do-pointer-to-pointers-work-in-c">How do pointer to pointers work in C?</a></p> <p><a href="https://stackoverflow.com/questions/758673/uses-for-multiple-levels-of-pointer-dereferences">Uses for multiple levels of pointer dereferences?</a></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. 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