How to change value of arguments in the function

后端 未结 4 570
南旧
南旧 2021-01-17 06:17

I try it :

#include 
#include 

void foo(int* x)
{
   x = (int *)malloc(sizeof(int));
   *x = 5;
}

int main()
{

   int a;
           


        
4条回答
  •  悲哀的现实
    2021-01-17 06:48

    You are changing the pointer value in foo by the malloc call - just do this:

    void foo(int* x)
    {
       *x = 5;
    }
    

    In your code - this function:

    void foo(int* x)
    {
       x = (int *)malloc(sizeof(int));
       *x = 5;
    }
    

    Works as follows:

    +----+
    | a  |
    +----+
    /
    x points here
    

    Then you make x point somewhere else:

    +----+                            +----+
    | 5  | /* created by malloc*/     | a  |
    +----+                            +----+
    / On Heap                         / On Stack
    x now points here                a is now in memory somewhere not getting modified.
    

    And you make it 5. Also note - x is a local copy of the &a address of a - in C there is no pass by reference but only pass by value - since the variables value is copied into the function.

提交回复
热议问题