2
A variable’s address is the location a variable’s value is stored. What does that
have to do with pointer? Well, a pointer is a variable, but addresses are the
values it holds. Wikipedia’s hyperlinks that lead to other wiki articles are pointers
to those articles. They use the address of the pages to point to their location.
A pointer is declared using the same data types as variables. To show the data
type is a pointer we add an * (asterisk) symbol: type* pointer_name or type
*pointer_name. A particular pointer type can only store address of the same
value type. This means, for example, int* can only store int addresses.
Let’s say we have an integer variable, number. We can declare an int pointer
called “ptr,” by putting an * (asterisk) before the name of our pointer. We can
then assign the reference to our integer variable to the pointer by using the &
(ampersand) symbol before out variable name: ptr = &number. If we output our
pointer (cout << ptr << endl), we will see the address to our variable, which we
can confirm by also outputting the reference to out variable (cout << &number
<< endl). What if we wanted to access the value inside the memory location?
We would then use the * (asterisk) symbol before our pointer’s name, cout <<
*ptr << endl. This would instead output the value inside of the address our pointer
holds.
Allocating Memory
Pointers don’t need to be assigned variable addresses. We can also allocate
the memory they use ourselves, as programmers. Our program allocates the
memory a pointer uses during run-time.
If we have an int pointer, ptr, we can allocate memory to the pointer using the
C++ operator new: ptr = new int. We can then assign value to the pointer by
dereferencing it using the * (asterisk). If we were to output the pointer, what
would be displayed? What if we output the dereferenced pointer?
Using the concept of dereferencing, we can perform arithmetic with our pointer.
In this case, we will add 10 to out pointer’s stored value. If we again output the
pointer, what will we see? What if we dereference it?
In both cases, we find that outputting the pointer displays an address. This
address remains the same even after performing arithmetic to our pointer’s
value, which does change.
What if we instead wanted to create an array? We would use the same new
operator, but instead add [] (square brackets): ptr = new int[SIZE]. Inside of the
brackets, we would need to declare the size of the array.