C++ Pointers

4/17/2016

I was having difficulty with pointers, so I thought I’d make a blog post on it


Pointers are a way of accessing the point in memory where the data is stored

In C++ when a variable is created it is assigned a point in memory. Sometimes, usually for performance reasons, we will need to find this address. One example of when this might be needed is when passing a large amount of data to a function. Instead of duplicating the data, we can pass an address for the data.


A variable which stores the address of another variable is known as a pointer


Address of operator

We can obtain the address of a variable by by preceding the name of the variable with an ampersand &. This is known as the address-of-operator.

int a = 10
int *addressOfA = &a;

In the example above a is going to be assigned into a point in the RAM.

The asterix * is needed for the syntax of of a pointer, but I shall discuss that later.

Variable Name a addressOfA
Value 10 7265
Memory Position 7265 Unkown, not needed

I have used 7265 as the address for simplicity, however in reality it is more liekly to look like this: 0x7fff57ec4b80

In the table above we can see how the memory is lain out, a has a value of 10 and is stored at the memory address of 7265. addressOfA has a value of 7265, which is the same as the memory address of a, at an unkown memory location. We should never need to know the location of a pointer, however &addressOfA would compile.


Deference Operator

The deference operator allows you to get the value from an address, it is the asterix symbol *. It can be read as “the value pointed to by”.

int b = *reference

When using the deference operator it has to be followed by a memory reference or a pointer.

Lets combine this ne knowledge with the previous example.

int a = 10
int *addressOfA = &a;

int b = *addressOfA;

a = 100
Variable Name a addressOfA b
Value 10 7265 10
Memory Position 7265 N/A N/A

Then after a = 100

Variable Name a addressOfA b
Value 100 7265 10
Memory Position 7265 N/A N/A

The important thing to note here is the even though we changed the value of A, the value of b stayed the same. This is becuase a has a different memory location to b.


As you may of noticed we assigned the value of a by doing

a = 100

however we could’ve used

*addressOfA = 100;

The 2 statements are equal


Pointers and functions

I mentioned earlier pointers can be useful for passing values into a function.

int func (int *ref) {
    *ref += 10;
    return *ref;
}

int c = func(addressOfA);

After the function executes a is 10 units larger, but c is not a pointer to a

For a more detailed tutorial look here: http://www.cplusplus.com/doc/tutorial/pointers/



Copyright Emily Peregrine © 2015
Admin Log In