Home Icon Home Resource Centre Pointers in C++ | A Roadmap To All Pointer Types (With Examples)

Pointers in C++ | A Roadmap To All Pointer Types (With Examples)

Pointers in C++ are variables that point to another variable or, more appropriately, they store the memory location/ address of another variable. We can use them to access and manipulate the values stored in that variable.
Shivani Goyal
Schedule Icon 0 min read
Pointers in C++ | A Roadmap To All Pointer Types (With Examples)
Schedule Icon 0 min read

Table of content: 

  • What Are Pointers In C++?
  • Pointer Declaration In C++
  • How To Initialize And Use Pointers In C++?
  • Different Types Of Pointers In C++
  • References & Pointers In C++
  • Arrays And Pointers In C++
  • String Literals & Pointers In C++
  • Pointers To Pointers In C++ (Double Pointers)
  • Arithmetic Operation On Pointers In C++
  • Advantages Of Pointers In C++
  • Some Common Mistakes To Avoid With Pointers In Cpp
  • Conclusion
  • Frequently Asked Questions
expand

The pointers in C++ programming are one of the most important topics anyone who wants to program in the language must be familiar with. In the general meaning of things, a pointer is what points to a thing, item, address, location, etc. Similarly, in terms of programming language, a pointer is a variable that points to the memory address of another variable, data, structure, etc. All in all, the pointer variable stores the memory location of a variable, which we can use to access and manipulate the data.

How does that work? Don't worry; by the end of this article, you will know all about pointers in C++ language, pointer declaration, types of pointers in C++, and more. 

What Are Pointers In C++?

Pointers in C++ are a unique type of variable that stores the address of another variable. That is, whenever we declare a variable in C++ programs, it is stored in the memory at a specific address. A pointer to that variable points to the address of the respective variable. In other words, the value stored inside a pointer is the address of the variable it points to.

Just like variables, functions, etc., pointers in C++ also have data types. For example, a pointer of data type int (integer) can store the address of the variable of int data type. Similarly, a pointer of data type float can store the address of the variable of float data type.

Visual explanation of pointers in C++ and what variable address means.

What Does Address Of A Variable Mean?

For you to understand the concept of pointers in C++ and all its surrounding topics, you must first understand what we really mean by the address of a variable. In C++ or any other programming language, when a variable is declared, its value gets stored at a specific location in the memory. This specific memory location is the address of the respective variable. And pointers are used to store the address of that value, which is stored in the memory. 

Pointer Declaration In C++

When declaring pointers in C++ programs, it is important to define the data type (or base type) of a pointer. And this data type (base type) of the pointer and the data type of the variable whose address is getting stored in the pointer should be the same, that is, they must take the same amount of space in memory.

Syntax For Declaring Pointers In C++

data_type *pointer_name;

Here,

  • Data_type refers to the type of the value/ data the pointer is pointing to.
  • The unary operator (*), also known as the dereference operator, indicates that the variable is a pointer. It is essential when declaring a pointer.
  • The term pointer_name is the placeholder for the name of the pointer you are creating. 

Syntax Examples for Pointer Declaration In C++

int *ptr; // Pointer of data type int
float *ptr; // Pointer of data type float
char *ptr; // Pointer of data type char
double *ptr; // Pointer of data type double

In the examples above, we first define the data type (int, float, char, double) and then the variable name with the unary operator (*). The asterisk sign is essential for valid pointer declarations as it indicates that the variable is a pointer type. It is also important to note that the actual valid address of a variable becomes apparent only at the runtime.

Note- In the declarations of pointers in C++, we use the unary operator (*) for each level of indirection. So if we are declaring a pointer to a pointer, then we will use one asterisk per pointer, i.e., **ptr.

Now, let's look at a simple C++ program that showcases how to create pointers and use them to access values stored in the variables they are pointing to.

Code Example:

Output:

10
10.5
x
1.345

Explanation:

In the C++ code example, we first include the essential header file for input-output operations, i.e., <iostream> and use namespace scope to use the header components directly. 

  1. In the main() function, we declare four pointer variables, ptr1, ptr2, ptr3, and ptr4, of different types, as mentioned in the code comment.
  2. Next, we declare four variables of different data types individually, assign values to them, and then assign their addresses to the respective pointers using the address-of operator (&).
  3. Now, all the pointers are pointing to a certain variable of the same data type as theirs.
  4. After that, we use a series of cout commands to print the values of the variables we created. But here, we use the pointers (ptr) to access these variables with the help of the indirection operator (*). 
  5. The main() function then terminates with a return 0 statement. 

How To Initialize And Use Pointers In C++?

Simply declaring pointers in C++ programs does not automatically mean that it is initialized and ready to use. That is, to use pointers in C++, we must declare and initialize them. We have already discussed how to declare pointers. For initialization, we must assign value to the pointers using the address-of operator (&). That is, assign the address of a variable to a pointer. For example, the following code fragment declares an integer variable named var and makes ptr point to it:

int var = 10;
int* ptr = &var;

Now, ptr points to the memory location of the variable. We can use the unary/ built-in indirection operator (*) to access the value stored at that location, as shown in the example above. There are three primary ways to initialize pointers in C++, which we have shown below.

1. Declare the pointers in C++ and assigning values separately

int var; //declaring the variable
int * ptr; //delaring the pointer
ptr = &var; //assigning value to the pointer using address-of operator

2. Declare and assign the value to pointers in C++ in one line

int var; //declaring the variable
int * ptr = &var; //declaring the pointer and assigning value to it in the same line

3. Pointers in C++ can also be initialized to store the value of another pointer

int var; //declaring the variable
int *ptr1 = &var; //declaring the pointer and assigning value to it
int *ptr2 = ptr1; //declaring another pointer and assigning a value of another pointer

You must now be able to declare, initialize and use pointers in C++ programs efficiently. Given below is another example of C++ code that shows how to create pointers and use them.

Code Example:

Output:

Value of the pointer ptr = 0x7fffa8645cac
Value of the variable var = 10
Value stored in pointer *ptr = 10

Explanation:

In the sample C++ code-

  1. We initialize an integer type variable var with the value 20 inside the main() function
  2. After that, we declare a pointer of type integer, ptr and then assign the address of var to it, using the address-of operator (&).
  3. Next, we use a set of cout commands to print the value of the pointer ptr, the value of the variable and the value stored at the location pointed to by ptr.
  4. This shows how we can use a pointer as is and also access the variable it is pointing to.

Time Complexity: O(1)
Space Complexity: O(1)

Different Types Of Pointers In C++

There are multiple different types of pointers in cpp classified on the basis of their nature, behaviours, use, values they point to, etc. The most commonly used type of pointers in C++ are-

  1. Null Pointers
  2. Dangling Pointers
  3. Void Pointers
  4. Wild Pointer
  5. Invalid Pointers

We will discuss each of these pointer types in the sections ahead, along with proper code examples.

Null Pointer In C++

In C++, when a pointer variable is assigned, the value NULL is called a null pointer. In other words, a null pointer is the type of pointer that does not point to anything. This pointer has many uses in programming, including checking for memory allocation when done dynamically, creating other pointers, avoiding memory leaks, etc. In cases where we do not have an exact address to be assigned to a pointer, it is best practice to assign it the NULL value to avoid unauthorised access or unexpected behaviour.

In C++, the null pointers have a constant value of zero, and they are defined in many C++ standard libraries. The pointer in C++ program example below showcases the working of a null pointer.

Code Example:

Output:

The value of the null pointer is 0

Dangling Pointer In C++

A pointer that is pointing to a memory location that has either been freed or deleted, is referred to as a dangling pointer. It means that the actual address/ memory location that is being assigned to the pointer has been deallocated or is otherwise invalid to be dereferenced.

A dangling pointer in C++ may occur when we use the free() function to clear/ free the space allocated to a pointer from the heap memory. It is best to reassign the NULL value to the ptr after free() to avoid the creation of dangling pointers.

Code Example:

Output:

0x1f7f010
0

Void Pointer In C++

As the name suggests, a pointer that isn't associated with any data type is called a void pointer, which is a special type of pointer in C++. A void pointer is also called a general-purpose pointer. Void pointers represent a pointer to an object/ variable of any data type without specifying its type. 

In other words, these are pointers that point to a value with no concrete data type (i.e. has undetermined length and undetermined dereferencing properties). So, when we assign the address of a character variable to a void pointer, the pointer takes on the data type of the variable, i.e., becomes a character type pointer. Similarly, if we assign an int data type address to a void pointer, it becomes an integer type pointer.

Important Considerations for Void Pointers in C++:

  • We cannot dereference void pointers directly, until and unless we typecast it to an actual data type.
  • Pointer arithmetic is not possible on void pointers due to the lack of a fundamental data type and, thus, size.

Code Example:

Output:

Integer variable = 2
Float variable = 2.500000

Note: Void pointers are also commonly used in data structures such as binary trees, linked lists, etc. These data structures are designed to work with any type of data, so they often use void pointers to store pointers to the actual data.

Wild Pointer In C++

As the name suggests, a wild pointer is a pointer that has an unpredictable behavior (and is hence wild) because it hasn't been initialized. In other words, it occurs when a pointer variable points to an undefined or invalid address/ memory location. Wild pointer often leads to program crashes, data corruption, or security vulnerabilities.

Example:

Output:

The value of variable x is: 10

Invalid Pointers In C++

An invalid pointer is a pointer that points to an undefined or unexpected memory address. This includes uninitialized pointers, pointers that have been assigned nullptr, or a pointer that points to a location in memory that has been deallocated. We cannot dereference such pointers; otherwise, it will lead to undefined behaviour.

Code Example:

Output:

Run Time Error/ Segmentation Fault

Explanation:

In the above example, the pointer ptr is initialized to null, meaning it does not point to a valid memory location. When we try to dereference the pointer using the * operator, we are trying to access the value at an undefined memory address, which can cause a segmentation fault or other runtime error. 

Explanation of difference between references and Pointers in C++

References & Pointers In C++

The purpose of references and pointers in C++ is to provide access to another variable. Both of these are created using the ampersand symbol (&), also called the address-of operator. It hence becomes difficult to differentiate between the two. Here is a brief description of both to provide a clear picture.

Pointers: Pointers in C++ are a special type of variable that stores the memory address of another variable. For example:

int var=10;
int *ptr = &var;

References: On the other hand, references are used to create aliases, i.e., alternative names for a variable declared previously with another name. This allows us to refer to a single variable with multiple names without creating copies of the variable. 

int var=10;
int &ref = var;

Irrespective of this, pointers and references are closely related since both allow us to access the data stored in another variable/ location indirectly. Think of it like this- pointers also act as references to a variable by allowing access to its location. Both references and pointers in C++ are widely used to pass arguments to functions. The relation between references and pointers can also be understood by looking at the ways of passing arguments to a function. These include:

  • Call by value
  • Call-By-Reference with Pointer Argument
  • Call-By-Reference with Reference Argument

Let’s take a look at an example to see the implementation of these methods and get a better understanding of them.

Code Example :

Output:

Value of variable var: 10
Value of variable var: 20
Value of variable var: 30

Explanation:

In the above code, we have called three functions where be pass parameters in three different ways, i.e., by value (variable name), by reference with a pointer argument, and by reference with a reference argument. 

Indirection Or Dereferencing Operator (*) For Pointers In C

In C++, an indirection or dereferencing operator is used with the pointer variable to represent the value of another variable. The dereference operator is denoted with an asterisk (*).

Example:

int var=10;
int *ptr;
p=&var;
//Now *ptr will print the value of var

Reference Operator (&) And Dereference Operator (*)

A reference operator is used to get the address of a variable. And the dereference operator(*) is used to get the “value pointed by” a pointer. Below is an example showcasing how these work in action.

Example:

Output:

10

Array pointers in C++ visual explaination, i.e., pointers to an array.

Arrays And Pointers In C++

As discussed, a pointer is a variable that stores the address of another variable. It is important to note that this characteristic is not limited to a single variable, that is, it can also store the address of every element of an array. When we assign an array to a pointer, the pointer variable essentially points to the first element of the array.

Code Example:

Note that we can access and manipulate all the elements in arrays using the pointer to array and array indices, which give the position of the elements of arrays. Just like in the example above where ptr=arr stores the address of the first element of the array, it is the same as ptr=&arrr[0];

So, when we want to point to another element of the array, we will use ptr + i. Here, ptr + 1 will point to the second element of the array. Similarly, ptr + 2 will point to the third element, and so on. That is-

ptr + 1 is equivalent to &arr[1];
ptr + 2 is equivalent to &arr[2];
ptr + 3 is equivalent to &arr[3];
ptr + 4 is equivalent to &arr[4];

Look at the example C++ program below to learn how you can use pointers to access array elements

Code Example:

Output:

Printing address using arrays:
&arr[0] = 0x61fef0
&arr[1] = 0x61fef4
&arr[2] = 0x61fef8

Printing address using pointers:
ptr + 0 = 0x61fef0
ptr + 1 = 0x61fef4
ptr + 2 = 0x61fef8

Explanation:

In this C++ example-

  1. We first declare an integer array with 4 elements (arr[4]) and an integer pointer ptr.
  2. Next, we use a for loop to access and print the address of all array elements. The loop begins loop variable i initially set to 0 and continues till i<4, incrementing it by 1 after every iteration. 
  3. Here, i refers to the index value/ position of the element of the array whose address is printed by the cout command inside the for loop.
  4. After that, we assign the array to the pointer ptr, so it points to the first element of arr. Then, print a string message using cout, where the newline escape sequence shifts the cursor to the next line before printing. 
  5. We once again create a for loop to print the addresses of array elements, but this time, we use the pointer, incrementing the value with every iteration to shift to the next position. 
  6. This shows how a pointer to an array initially points to the first element and can be used to access all elements. 

String Literals & Pointers In C++

Pointers and string literals are also important concepts in C++ and are widely used to manipulate strings/ textual data. In this section, we will discuss these literals and see how they can be used with pointers in C++.

What Are String Literals?

To begin with, string literals are representations of a sequence/ array of characters that form null-terminated character sequences. The element of these literals is of type const char (i.e., constant character) because it is not possible to modify the characters in a string. Also, the sequence of characters in a string literal (also known as a string constant) is enclosed in double quotes (" "). For example:

"Hello Unstoppable"
"Be Unstoppable"

String Literals As Pointers In C++

We know that string literals are stored as arrays of character sequences, implying that a string literal is also a pointer to the first character in the respective array. For example, “Hello Unstoppable” is the pointer to the first character ‘H’.

char *ptr=”Hello Unstoppable”;

Pointer ptr points to the first character of the string, which is ‘H’. To access other characters, we can use pointer arithmetic.

printf("%c" ,*(ptr+1) ); // prints e
printf("%c" ,*(ptr+2 ); // prints l

We can use pointers to string literals just like pointers to arrays and access/ manipulate the textual data stored in them.

Pointers To Pointers In C++ (Double Pointers)

A pointer that stores a memory address to another variable is referred to as a pointer variable. But if we define another pointer variable to store the memory address of the first pointer, it is known as a pointer to pointer or a double pointer in C++.

If we have a variable x=10, and we declare a pointer ptr1 to store its memory address and then declare another pointer ptr2 to store the memory address of pointer ptr1. Then, pointer ptr2 will be called pointer to pointer. We use a double asterisk(**) to represent pointer to pointer, that is, one asterisk per pointer/ level of indirection. 

Code Example:

Output:

Value of var :10
Value available at *ptr1 :10
Value available at **ptr2 :10

Arithmetic Operation On Pointers In C++

The most common arithmetical operations on pointers are addition, subtraction, increment, and decrement. Addition and subtraction operations on pointers involve adding or subtracting an integer value to or from the memory address stored in the pointer.

  • For example, if we have a pointer p that points to an integer x, we can add an integer n to the address stored in p to access the memory location of the integer n positions away from x.
  • Similarly, we can subtract an integer n from the address stored in p to access the memory location of the integer n positions before x.
  • We can also use the increment operator to get the increment pointer. That is, we can use the address stored in p to access the memory location of the next integer in memory.
  • Similarly, we can use the decrement operator and the address stored in p, to access the address in memory of the previous integer in memory.

In the example below, we will look at implementing all these arithmetic operations on pointers in C++.

Code Example:

Output:

ptr:0x7ffdaa84e7d0
Arithmetic Operations On Pointers:
ptr++: 0x7ffdaa84e7d4
ptr--: 0x7ffdaa84e7d0
ptr = ptr + 2: 0x7ffdaa84e7d8
ptr = ptr - 2: 0x7ffdaa84e7d0
d = q - ptr: 1

Explanation:

  1. We first declare and initialize an integer array named arr with 5 integer elements.
  2. Next, we initialize two interger pointers: ptr with the array and q with the array element at position 3.
  3. After that, as mentioned in the code comments, we perform a series of arithmetic operations on the original pointers using increment and arithmetic operators

Advantages Of Pointers In C++

Pointers in C++ are powerful tools that allow developers to manage memory manipulation and dynamic memory allocation effectively. Here are a few advantages of pointers in C++:

  • The primary advantage of using a pointer is instead of storing a value directly, a pointer stores the memory address of the value, allowing programs to manipulate the data directly.
  • Pointers allow programs to pass large data structures between functions without having to copy the entire structure.
  • Using pointers can also help optimize program performance by reducing the number of memory lookups needed to access data.
  • Pointers allow programs to manipulate data in memory directly, giving developers greater control over how data is used and stored. This is especially useful for handling dynamic data structures and complex data structures, such as linked lists, trees, graphs, etc.

Some Common Mistakes To Avoid With Pointers In Cpp

While pointers in C++ are essential, they also sometimes be confusing to use and lead to problems if not handled carefully. Below are a few important common mistakes that should be avoided while using pointers.

  • Not Initializing Pointers: One of the most common mistakes is not initializing pointers in C++. When you declare a pointer variable, it does not point to a specific memory address by default and leaving it uninitialized can lead to security issues.
  • Dangling Pointers: A dangling pointer is a pointer that points to a memory location that has been freed or deleted. This can lead to undefined behavior or even a crash.
  • Forgetting to Dereference Pointers: Dereferencing a pointer means accessing the value stored at the memory address pointed to by the pointer. Forgetting to dereference a pointer can result in errors or unexpected behavior.
  • Not Checking for NULL Pointers: NULL pointers are pointers that do not point to a valid memory address. If you try to access the value stored at a NULL pointer, you will get a segmentation fault.
  • Memory Leaks: Memory leaks occur when you allocate memory dynamically using functions like malloc() or new() operator but fail to deallocate it when it is no longer needed. This can lead to a shortage of memory, causing your program to crash.

Conclusion

Pointers in C++ serve multiple purposes such as for dynamic memory allocation and manipulation of data and data structures. While they can be tricky to use correctly, understanding how pointers work and being careful with memory management can lead to efficient and effective code.

It is important to remember always to initialize pointers, avoid dangling pointers, and properly deallocate memory to avoid memory leaks. With proper usage and care, pointers in C++ can be an invaluable asset to any programmer.

Frequently Asked Questions

Q. What is pointer vs pointer address?

Pointers in C++ are special variables that store the address of another variable. A pointer address is the memory address of a pointer variable. Like any other variable, a pointer variable is stored in memory, and its memory address can be accessed using the address-of operator, i.e., the ampersand sign (&).

Q. How do you declare a pointer of a pointer in CPP?

A pointer variable stores the memory address of another variable, but if we define another pointer variable to store the memory address of the first pointer, it is known as a pointer to a pointer. This is also referred to as a double pointer. 

Example:

int var = 23; //initializing an integer variable
int *ptr1 = &var; // declaring an integer pointer and assign a value to it
int **ptr2 = &ptr1; // declaring another pointer and storing previous pointer in it

Q. What do the asterisk (*) and ampersand (&) symbols indicate in the pointer in C++?

The asterisk and ampersand symbols are frequently used for the concepts of references and pointers in C++. Here is what they stand for:

  • Sign & is the reference operator or the address-of operator that is used to get the address of a variable.
  • Sign * is the dereference operator(*) used to get the value pointed by a pointer.

Q. Can a pointer point to two addresses?

No, a pointer cannot point to more than one address. That is, a pointer is a variable that stores the memory address of another variable, and it can only point to one memory address at a time. You can, however, reassign a pointer to point to a new variable if needed.

Q. How do you declare a pointer in a function declaration?

To declare a pointer in a function declaration, we need to specify the data type of the pointer and the function name, followed by the pointer variable name in parentheses.

void function_name(int *ptr) {
// Function body
}

Q. How do you declare a pointer array in CPP?

We know that a pointer is a variable that can store the address of another variable, but it is not limited to a single variable. It can also store the address of every element of an array. To declare a pointer array in C++, you can use the following syntax:

data_type* pointer_array_name[size];

The concept of pointers in C++ is integral to writing efficient codes. Here are a few other important topics you must explore:

  1. Logical Operators In C++ | Use, Precedence & More (With Examples)
  2. C++ If-Else | All Conditional Statements Explained With Examples
  3. Pointer To Object In C++ | Simplified Explanation & Examples
  4. The 'this' Pointer In C++ | Declaration, Constness, Applications & More
  5. OOPs Concept In C++ | A Detailed Guide With Codes & Explanations
Edited by
Shivani Goyal
Manager, Content

I am an economics graduate using my qualifications and life skills to observe & absorb what life has to offer. A strong believer in 'Don't die before you are dead' philosophy, at Unstop I am producing content that resonates and enables you to be #Unstoppable. When I don't have to be presentable for the job, I'd be elbow deep in paint/ pencil residue, immersed in a good read or socializing in the flesh.

Tags:
Engineering Computer Science

Comments

Add comment
comment No comments added Add comment
Powered By Unstop Logo
Best Viewed in Chrome, Opera, Mozilla, EDGE & Safari. Copyright © 2024 FLIVE Consulting Pvt Ltd - All rights reserved.