What is the real difference between Pointers and References?

后端 未结 22 2800
南方客
南方客 2020-12-01 04:33

AKA - What\'s this obsession with pointers?

Having only really used modern, object oriented languages like ActionScript, Java and C#, I don\'t really understand the

22条回答
  •  一生所求
    2020-12-01 05:06

    Since you have been programming in object-oriented languages, let me put it this way.

    You get Object A instantiate Object B, and you pass it as a method parameter to Object C. The Object C modifies some values in the Object B. When you are back to Object A's code, you can see the changed value in Object B. Why is this so?

    Because you passed in a reference of Object B to Object C, not made another copy of Object B. So Object A and Object C both hold references to the same Object B in memory. Changes from one place and be seen in another. This is called By Reference.

    Now, if you use primitive types instead, like int or float, and pass them as method parameters, changes in Object C cannot be seen by Object A, because Object A merely passed a copy instead of a reference of its own copy of the variable. This is called By Value.

    You probably already knew that.

    Coming back to the C language, Function A passes to Function B some variables. These function parameters are natively copies, By Value. In order for Function B to manipulate the copy belonging to Function A, Function A must pass a pointer to the variable, so that it becomes a pass By Reference.

    "Hey, here's the memory address to my integer variable. Put the new value at that address location and I will pick up later."

    Note the concept is similar but not 100% analogous. Pointers can do a lot more than just passing "by reference". Pointers allow functions to manipulate arbitrary locations of memory to whatever value required. Pointers are also used to point to new addresses of execution code to dynamically execute arbitrary logic, not just data variables. Pointers may even point to other pointers (double pointer). That is powerful but also pretty easy to introduce hard-to-detect bugs and security vulnerabilities.

提交回复
热议问题