How to change value of arguments in the function

后端 未结 4 526
南旧
南旧 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:01

    • foo(&a); Passes the address of a variable to a function.

    • void foo(int* x) That address passed is now copied and stored in x. x is a pointer variable local to the function.

    • x = (int *)malloc(sizeof(int));. Here you overwrite the contents of x with a completely different address, to dynamically allocated memory.

    • *x = 5; Here you assign the value 5 to that memory, which resides on the heap.

    • } Here you forgot about everything you did in the function. You create a memory leak since you didn't free() the memory. Apart from that, the function has done nothing that affects the rest of the program. It only fiddled around with the local variable x.

    • printf("%d\n",a); Here you print the contents of the uninitialized variable a, which has not been altered by the function.

    In addition, it never makes sense to cast the result of malloc in C. Also, malloc is found in stdlib.h. Don't use malloc.h, that's a superfluous, non-standard header.

提交回复
热议问题