How to change value of arguments in the function

后端 未结 4 528
南旧
南旧 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 07:10

    In foo, variable x is a local variable, a pointer to an int - it is a variable containing a value which is the address of an int in memory.

    You are calling the function with the address of main's a variable. But then you are changing x

    x = (int *)malloc(sizeof(int));
    

    This changes x to be a different value, the address of an area of memory now reserved for our use. HOWEVER, x is a variable local to foo. When foo ends, x goes away, and we return to main. Two things have happened:

    1. We have allocated some memory,
    2. We have assigned a value to it.

    You then print out the contents of mains a. a is still at the same location it was before we called foo.

    Perhaps this previous answer to a related question will help you: Pointer errors in the method of transmission(c++)

提交回复
热议问题