understand passing parameters by reference with dynamic allocation

前端 未结 5 2059
难免孤独
难免孤独 2021-01-25 16:59

I\'m trying understand how to pass a parameter by reference in C language. So I wrote this code to test the behavior of parameters passing:

#include 

        
5条回答
  •  死守一世寂寞
    2021-01-25 17:48

    Actually not really much a difference, except the first one is broken. :) (Well, both are, but the first is broken more).

    Let me explain what happens in the second case:

    • variable n of type pointer-to-int is allocated on the stack
    • a new variable of type int is allocated to the stack, it's address is stored in variable n
    • function alocar is called, being passed the copy of variable n, which is the copy of the address of our variable of type int
    • the function sets the int variable being pointed by n to 12
    • the function prints the value of the variable being pointed by n (12)
    • the function returns

    The first case:

    • variable n of type pointer-to-int is allocated on the stack
    • the function alocar is called with a copy of the variable n (which is still uninitialized - contains an unknown value)
    • a new variable of type int is created in memory and the local copy of variable n in function alocar is set to point to that new variable
    • the variable (pointed by the function's local copy of n) is set to 12 and printed
    • the function returns, again in the main() function:
    • since the original n variable in main is still uninitialized, it points to a random place in memory. So the value in random place in memory is printed (which is likely to crash your program).

    Also, both programs are broken because they don't free the memory allocated by malloc().

提交回复
热议问题