Pointers -> pointing you in the right direction;

If you are reading this then you must be looking for a simple explanation on C++ pointers or not. It is a tricky concept to grasp at first, however it looks harder than it is.

Lets take a look at a very simple example:

We can see from line 7 that we are creating a pointer i that actually points to a type int. This is what is a bit tricky to understand. A pointer is not the same type that it points to. A pointer is merely a location in memory that can be referenced by its address.

“pointer = location in memory” Remember this and you will be fine.

Back to line 7, we declare a pointer using the asterisk* . In order to access the data the pointer points to we need to use the asterisk* again. This means that if we need to change the value or read the data from the memory location pointed to by the pointer we simply need to dereference the pointer using the asterisk.

A quick recap:

  • line 7 we use the asterisk to declare the pointer
  • line 9 we use the asterisk to dereference the pointer and assign a value
  • line 11 we use the asterisk to dereference the pointer to obtain the value it points to.

Now some of you may be thinking “surely standard data types must have an address in memory as well?” and the answer to that is yes they do. We can access the location of a variable using the “&” operator. Consider the following code:

Line 7: declare variable of type int

Line 9: declare pointer that will point to a memory location with data type int

Line 11: we assign ptr with the address of x using the & operator. (careful here we are NOT assigning the value of x but rather the address of x)

Note: Be careful when applying this method as pointing to the address of a variable that has gone out of scope will lead to your program not running as expected. If a variable goes out of scope its memory address will still have a value stored there, thus your program may seem to operate OK until that memory address is used by something else in which case the value stored there will be overwritten.

There you have it, pointers put simply.

Photo by Hello I’m Nik

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s