reset password
Author Message
kknaur
Posts: 540
Posted 17:45 Feb 21, 2014 |

What is the difference between a pointer and a reference?

I got asked this question in email, and I wanted to post my answer here for everyone to see:

At first glance, there may not seem like there is much of a difference between pointers and references.  They both refer to memory addresses, they both can be used for call-by-reference, and usually a reference is implemented as a constant pointer in memory (datatype * const ptr_name), however, this implementation is a bit abstracted to make references easier to understand and work with than pointers.

The main difference is in how you use them.  References are mainly used when you want to have call-by-reference parameters to a function.  They can also be used when you want to return a reference from a function.  When you return a reference, you have to be careful that you do not return a reference to anything created locally in the function (i.e. anything created on the stack).  As you know, when the function returns this stack memory becomes garbage.

Pointers are used whenever you want to use the dynamic or "heap" memory, i.e. whenever you use the new keyword.  You have to assign the return value of new to a pointer because new returns a pointer type not a reference type.

If you want some more specific differences between pointers and reference I suggest you take time to read this thread on StackOverflow.  It has a very good explanation of this.

My general rule of thumb when deciding on whether or not to use a pointer or a reference is this (also in the slides):

  • If you can use a reference use a reference.
  • If you need to use a pointer then use a pointer.
    • anything created with the new keyword
    • dynamic arrays
    • don't forget to free up the memory
    • don't forget to set the pointer to NULL
  • If it doesn't matter which one you use, most people seem to prefer references over pointers.

Keenan Knaur

Last edited by kknaur at 17:47 Feb 21, 2014.