Cpp - Pointer Pointer Introduction

Introduction

To declare a pointer called pAge to hold address of an int, use the following statement:

int *pAge = nullptr; 

This declares pAge to be a pointer to int. That is, pAge is declared to hold the address of an int.

In this example, pAge is initialized to nullptr, which represents a pointer whose address points to nothing in C++.

A pointer with this value is called a null pointer.

All pointers, when they are created, should be initialized.

By default, you can assign nullptr to them.

You also might see pointers initialized to 0, like this:

int *pAge = 0; 

The following code assign the address of age to pAge. Here's code to do that:

int age = 50;     // make a variable 
int *pAge = nullptr; // make a pointer 
pAge = &age;      // put age's address in pAge 

The first line creates a variable age, whose type is int, and initializes it with the value 50.

The second line declares pAge to be a pointer to type int and initializes the address to nullptr.

The third line assigns the address of age to the pointer pAge.

You could have accomplished this with fewer steps:

int age = 50;                 // make a variable 
int *pAge = &age;   // make pointer to age 

Indirection Operator

The indirection operator * returns the value at the address stored by the pointer.

For example,

int age = 50;        // create the variable age 
int *pAge = &age;    // pAge points to the address of age 
*pAge = 5;              // assign 5 to the value at pAge 
int yourAge;            // create another variable 
yourAge = *pAge;        // assign value at pAge (50) to yourAge 

The indirection operator * in front of the variable pAge means "the value stored at."

Related Topics

Exercise