In C++, a pointer holds the address of an object stored in memory. The pointer then simply “points” to the object. The type of the object must correspond with the type of the pointer.
type *name; // points to a value of the specified type
type
refers to the data type of the object our pointer points to, and name
is just the label of the pointer. The *
character specifies that this variable is in fact, a pointer. Here is an example:
int *p; // integer pointer
string *q; // string pointer
The &
character specifies that we are storing the address of the variable succeeding it.
The *
character lets us access the value.
#include <iostream>using namespace std;int main() {int var = 10;int *p;p = &var; // p points to the address of varcout << "The address stored in p: " << p << endl;cout << "The value that points to: " << *p << endl;*p = 15; // update the value of pcout << "The new value of var is: " << var << endl; // var is updated!var = 20; // the value of var is updatedcout << "The new value of *p and var: " << *p; // p has been updated as well!}
So, why do we need pointers when we already have normal variables? Well, with pointers we have the power of creating new objects in dynamic memory rather than static memory. A pointer can create a new object in dynamic memory by using the new
command.
#include <iostream>using namespace std;int main() {int *p = new int; // dynamic memory reserved for an integer*p = 10; // the object is assigned the value of 10cout << "The value of the object p points to: " << *p << endl;int *q = p; // both pointers point to the same objectcout << "The value of the object q points to: " << *q << endl;}
Syntax | Purpose |
---|---|
int *p |
Declares a pointer p |
p = new int |
Creates an integer variable in dynamic memory and places its address in p |
p = new int[5] |
Creates a dynamic array of size 5 and places the address of its first index in p |
p = &var |
Points p to the var variable |
*p |
Accesses the value of the object p points to |
*p = 8 |
Updates the value of the object p points to |
p |
Accesses the memory address of the object p points to |