Summary: In this tutorial, we will learn what are pointers in C++, how to create and use a pointer, and how to modify variable using pointers in C++.

Introduction to Pointers in C++

A Pointer is a variable that stores the memory address of another variable or object.


Since a pointer stores the address of another variable, it can reference the variable by address.

What is Memory Address?

The values of every variable and object are stored in the memory at some respective address. These addresses in context to a programming language are the memory addresses for variables or objects.

A memory address is usually of the hexadecimal form i.e. preceded with 0x. It can be accessed by preceding the variable name with an ampersand (&) operator.

For example, the following program is printing the address of a string variable:

Since we now know what a pointer is, let’s see how to create one in C++.

How to Create and Use a Pointer in C++?

The general syntax to declare a pointer in C++ is:

where the type is the type of the variable or object whose address the pointer will store. It can be a primitive or user-defined type.

Declaring a pointer is not enough. It has to store the address of a variable or an object.

We can assign to the pointer the address of a variable using the & operator. Once done, we can obtain the value pointed to by a pointer variable using the dereference reference operator  (*), like the following example:



We can also modify the value pointed to by a pointer using the dereference reference operator.

Here is a C++ example in which we are modifying the value of the pointed string variable:



Common Mistakes with Pointers

We should be type cautions when working with pointers. We often confuse between address and value that causes ambiguity in our program.

Consider the following examples using pointers:

Next on Pointers:

In this tutorial, we learned what memory address and pointer are in C++. We learned to create and modify a variable’s value using a pointer in the C++ programming language.

Leave a Reply