understand passing parameters by reference with dynamic allocation

前端 未结 5 2011
难免孤独
难免孤独 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:56

    See, what's happened in first program.

    Before call to alocar we have just variable n in main, pointing to some undefined place:

     main()::n [  X--]--->(?)
    

    (there's value in square brackets, which is undefined, marked as X). Then we call alocar, and we have another variable in alocar's scope, which have a copy of origianl var.

     main()::n   [  X--]--->(?)
     alocar()::n [  X--]-----^
    

    Now, allocate some memory:

     main()::n   [  X--]--->(?)
     alocar()::n [  *--]--->[   Y  ]
    

    Assign value to allocated var:

     main()::n   [  X--]--->(?)
     alocar()::n [  *--]--->[  12  ]
    

    Return. alocar()::n is removed as it live only while alocar() is executed.

     main()::n   [  X--]--->(?)
                            [  12  ]
    

    main()::n is still pointing to some undefined place... (Which possibly stores value 0) And no one points to allocated place.

提交回复
热议问题