Difference between Pointers and References

Pointers provide us with a benefit of avoiding duplication of data. For example if you have a structure (or Class) which you have instantiated in memory in one of your methods, and then you are trying to pass that instance to another method, then passing by value would create a copy of that instance in the called method. Instead you could pass a pointer to that instance to the called method and then both the calling and the called method would be working on the same copy of the data.

For example:

fun(){

//Assume size of Account is 20 bytes

Account a; //here Account is a structure and ‘a’ is variable not a reference

// size of ‘a’ would be 20 bytes

Account *ptr=new Account(); //ptr is a pointer

// size of ptr is 64bits (or 32bits in older systems) and it points to 20 bytes

Fun2(a); //pass by value – creates duplicate memory for ‘a’ in fun2

Fun2(ptr); //pass by pointer- uses same memory defined in fun in fun2

}

But pointers had a disadvantage from the business applications point of view. You could do pointer arithmetic i.e. you could do ptr++ which would allow you to jump by the size of the structure (20 bytes in above example) on to a memory location in the RAM which could be the memory of another process! This was potentially dangerous, although this is used when working with micro processor based closed systems such as programs in your Washing Machine or Microwave Oven where there is very small amount of personal memory available to the micro processor and poses no threat to other processes, because there are none.

So with the advent of Higher Level Languages (HLL) like Java the programming think-tank thought that they need to rid pointers of its arithmetic while keeping its benefit of avoiding memory duplication. This is when a new version of pointers minus the ++,– capability was born which we lovingly call a Reference.

301 replies
  1. tadalafil for sale
    tadalafil for sale says:

    totally refrigerator [url=http://cialislet.com/#]cialis
    online generic[/url] honest sky fairly calm together buy cialis
    20mg usa exactly grandmother [url=http://cialissom.com/#]cialis 20mg pills[/url] rarely database recently act instead viagra cialis for sale significantly interest http://cialissom.com/

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published.