Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In C, <strong>everything is passed by value</strong>.</p> <p>What you are passing to fun() is a <strong>copy</strong> of the pointer you have in main().</p> <p>That means the <strong>copy</strong> of ptr is aimed at the allocated memory, and that memory set to 115.</p> <p>The ptr in main() still points at an undefined location because it has never been assigned.</p> <p>Try passing <strong>a pointer to the pointer</strong>, so that within <code>fun()</code> you have access to the pointer itself:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int* fun(int**); // &lt;&lt;-- CHANGE int main() { int a=5; int* ptr; // ptr=(int*)malloc(sizeof(int)); fun(&amp;ptr); // &lt;&lt;-- CHANGE a=*ptr; printf("\n the val of a is:%d",a); return 0; } int* fun(int** another_ptr) // &lt;&lt;-- CHANGE { *another_ptr = (int*)malloc(sizeof(int)); // &lt;&lt;-- CHANGE **another_ptr = 115; // &lt;&lt;-- CHANGE return *another_ptr; } </code></pre> <p>The other option would be to make <code>fun()</code> actually return the updated pointer (as advertised), and assign this to ptr:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int* fun(int*); int main() { int a=5; int* ptr; // ptr=(int*)malloc(sizeof(int)); ptr = fun(ptr); // &lt;&lt;-- CHANGE a=*ptr; printf("\n the val of a is:%d",a); return 0; } int* fun(int* another_ptr) { another_ptr = (int*)malloc(sizeof(int)); *another_ptr = 115; return another_ptr; // &lt;&lt;-- CHANGE } </code></pre> <p><strong>Edit:</strong> I renamed the variable in <code>fun()</code> to make it clear that it is <strong>different</strong> from the one you use in <code>main()</code>. Same name doesn't mean anything 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. 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