Taylor's Blog

Atypical ramblings

References & Pointers

This week our class has finally encountered pointers. I knew that it would be a challenging subject, so I’m trying to take it slow. There are a couple of questions I have been trying to resolve in my mind since encountering these two concepts. The first one is: what is the point of pointers?

That’s where I discovered this comment on reddit that I feel applies to both pointers and references:

The best metaphor I’ve found for pointers are websites.

You could copy and paste the contents of a website into a document and then send that to someone, or you can send a pointer (the URL) to them.

The benefit of the pointer is if the site gets updated, you both see the changes, whereas if you send a pasted document, they will never see any changes.

If you just use the variable, it’s copying the whole contents of the variable. Whereas if you use a pointer/reference, it’s sending a lot less data and using a lot less memory.

Another difficult questions I’ve been working on answering is what the difference is between pointers and references. For that answer, I went to StackOverflow:

Use reference wherever you can, pointers wherever you must.

Avoid pointers until you can’t.

The reason is that pointers make things harder to follow/read, less safe and far more dangerous manipulations than any other constructs.

So the rule of thumb is to use pointers only if there is no other choice.

I’m sure there is more to it than that, but feel that those cover the basics pretty well. Now for actually learning the syntax. I wrote a little program to help remind myself of the finer points:

 int myInt;
 int *myPointer;
 myPointer = &myInt;
 *myPointer = 5;
 cout << "myPointer points to address " << myPointer << endl; //outputs address
 cout << "The value stored at that address is " << *myPointer << endl; //outputs 5

 //An array name, without brackets and a subscript, actually represents the starting 
 //address of the array. This means that an array name is really a pointer.
 int myArray[] = { 10, 20, 30 };
 cout << *myArray << endl; //outputs 10

 //These two lines do the same thing:
 cout << myArray[1] << endl; //outputs 20
 cout << *(myArray + 1) << endl; //outputs 20

 //This adds 1 to the first value in the array:
 cout << *myArray + 1 << endl; //outputs 11

 int *arrayPoint; //This is a pointer that points to an int (or an array of ints)
 arrayPoint = myArray; //Assign it to an array to point to
 cout << *arrayPoint << endl; //outputs 10
 cout << *arrayPoint << endl; //outputs 20

I’ll add some more notes for pointers and references later.

Updated: November 17, 2015 — 11:27 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

Taylor's Blog © 2015