C++ Pointers - C++ Programming Tutorial

C++ Pointers

BLUF: Mastering C++ Pointers is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Pointers

C++ is renowned for its efficiency. Learn how C++ Pointers enables low-level control and high-performance computing in the tutorial below.

In the C++ programming language, a pointer serves as a variable referred to as a locator or indicator, directing to the memory address of a specific value. The pointer symbol, denoting an address, is signified by the (*) asterisk symbol. Besides facilitating the creation and alteration of dynamic data structures, pointers enable programs to implement call-by-reference functionality.

One of the primary uses of pointers in C++ is to traverse arrays and other data structures. In C++, we can define the pointer variable with the identical data type as the elements in the array and assign it the address of the initial element. This enables us to directly access and modify the data through pointer arithmetic.

Syntax

It has the following syntax:

Example

datatype *var_name;   

int *ptr;   // ptr can point to an address which holds int data

In this particular format,

  • datatype: This signifies the specific data type that is specified for the pointer.
  • var_name: This denotes the identifier assigned to the pointer.
  • Assigning Addresses to Pointers

In C++, the addressof operator (&) is primarily utilized to save the memory location of a variable. Subsequently, this memory address can be assigned to a pointer variable to initialize it.

Example:

Example

int num = 45;

int *ptr = #

In this instance, ptr symbolizes the pointer that holds the memory location of variable num by utilizing the addressof operator (&).

Dereferencing the Pointer

In C++, the act of dereferencing involves retrieving the value stored in a specific memory address. This action is carried out through the utilization of the dereference operator, denoted by the (*) symbol.

C++ Pointer Example

Let's consider a scenario to demonstrate the pointer concept in C++.

Example

Example

#include <iostream>  

using namespace std;   //using standard namespace

int main()   //main function

{  

int number=45;    

int *p;      

p = &number; //stores the address of number variable    

cout<<"Address of number variable is: "<<&number<<endl;    

cout<<"Address of p variable is: "<<p<<endl;    

cout<<"Value of p variable is: "<<*p<<endl;    

   return 0;  

}

Output:

Output

Address of number variable is: 0x7ffc7d468acc

Address of p variable is: 0x7ffc7d468acc

Value of p variable is: 45

Explanation:

In the given illustration, an integer value is selected along with a pointer named p, which holds the memory location of the value. Subsequently, the code retrieves the value stored at the memory address pointed to by p and displays it.

How to use a pointer in C++?

If we want to create a pointer in C++, we have to follow the following steps.

  • First, we have to create a pointer variable.
  • After that, we have to use the unary operator (&), which yields the address of the variable, to assign a pointer to a variable's address.
  • Using the unary operator (*), which gives the variable's value at the address provided by its argument, we can access the value stored in an address.

When we work with a data type, it contains information about the number of bytes it occupies, and this information is linked with a reference. As we move a pointer to the next location, the size of the data type it points to is considered and accounted for.

Symbols Used in Pointer

There are typically two symbols that are commonly utilized in C++ pointers.

Symbol Name Description
& (ampersand sign) Address operator Determine the address of a variable.
∗ (asterisk sign) Indirection operator Access the value of an address.

C++ Pointer example to swap two numbers without using a third Variable

Let's consider an instance to demonstrate how we can exchange two values without the need for a third variable in C++.

Example

Example

#include <iostream>  

using namespace std;   //using standard namespace

int main()   //main function

{  

int a=20, b=10, *p1=&a, *p2=&b;    

cout<<"Before swap: *p1="<<*p1<<" *p2="<< *p2<<endl;    

*p1=*p1+*p2;    

*p2=*p1-*p2;    

*p1=*p1-*p2;    

cout<<"After swap: *p1="<<*p1<<" *p2="<<*p2<<endl;    

   return 0;  

}

Output:

Output

Before swap: ∗p1=20 ∗p2=10

After swap: ∗p1=10 ∗p2=20

Explanation:

In this instance, we interchange the values of two integers by leveraging pointers and arithmetic calculations without the need for a temporary variable. Initially, we sum the values indicated by p1 and p2, followed by individual adjustments to finalize the exchange. Subsequently, the script displays the values both pre and post-swap, showcasing the manipulation and dereferencing of pointers.

Types of Pointers

There exist various categories of pointers in C++. Some primary varieties of pointers include:

Null Pointer

In C++, a null pointer is a pointer that is set to the value nullptr (or NULL) and does not point to any valid memory location. It is primarily used to initialize a pointer when we do not intend for this null pointer to reference any object.

Syntax

It has the following syntax:

Example

int *ptr1 = 0;  

int *ptr2 = NULL;

C++ Null Pointer Example

Let's consider an example to demonstrate the concept of the null pointer in C++.

Example

#include <iostream>

using namespace std;  //using standard namespace

int main()  //main function

{

    // NULL pointer

    int *ptr = NULL;   

    return 0;

}

Void Pointer

In C++, a void pointer serves as a unique pointer that can reference any data type. Direct dereferencing is not supported with void pointers. To access the data, they need to be casted into a pointer of a particular data type.

Wild Pointer

In the C++ programming language, a stray pointer is a pointer that has been assigned a memory address but points to an arbitrary location in memory.

Syntax

It has the following syntax:

Example

int *ptr;  // Wild pointer

*ptr = 10; // Undefined behavior

Dangling Pointer

In C++, a dangling pointer refers to a pointer that points to a memory location that has been deleted or freed. This type of pointer behaves like a wild pointer, which can lead to errors in C++ programs.

Syntax

It has the following syntax:

Example

int *ptr = new int(5);

delete ptr;   // ptr is now dangling

Smart Pointer

In C++, smart pointers are class templates offered by the STL to handle dynamic memory allocation automatically. They act as a protective layer around pointers by implementing overloaded operators like * and ->. Smart pointers handle memory deallocation automatically when it's no longer needed, effectively preventing issues like memory leaks and dangling pointers.

Pointer to a Pointer

In C++, it is possible to create a pointer that points to another pointer, which can further point to either data or another pointer. To indicate each level of indirection, the unary operator (*) is essential in the syntax when defining the pointer.

C++ Pointer to Pointer Example

Let's consider an example to demonstrate the concept of pointer to pointer in C++.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

 

int main() {   //main function

    int num = 18;

    

    // Store the address of var variable

    int *ptr1 = &num;

    int **ptr2 = &ptr1;

    

    // Accessing values

    cout << *ptr1 << endl;

    cout << **ptr2;

    return 0;

}

Output:

Output

18

18

What are References and Pointers in C++?

In C++, reference and pointer seem to be similar, but some differences exist between them. A reference is a variable that is another name of the existing variable, while the pointer is a variable that stores the address of another variable.

  • Call-By-Value
  • Call-By-Reference with a Pointer Argument
  • Call-By-Reference with a Reference Argument
  • Example

Example

#include <iostream>

using namespace std;    //using standard namespace

// Pass-by-Value  

int square1(int n)  

{cout << "address of n1 in square1(): " << &n << "\n";  

n *= n;  

return n;  

}  

// Pass-by-Reference with Pointer Arguments  

void square2(int* n)  

{  

cout << "address of n2 in square2(): " << n << "\n";  

*n *= *n;  

}  

// Pass-by-Reference with Reference Arguments  

void square3(int& n)  

{  

      

cout << "address of n3 in square3(): " << &n << "\n";  

n *= n;  

}  

void example()  

{  

    // Call-by-Value  

    int n1 = 8;  

    cout << "address of n1 in main(): " << &n1 << "\n";  

    cout << "Square of n1: " << square1(n1) << "\n";  

    cout << "No change in n1: " << n1 << "\n";  

  

    // Call-by-Reference with Pointer Arguments  

    int n2 = 8;  

    cout << "address of n2 in main(): " << &n2 << "\n";  

    square2(&n2);  

    cout << "Square of n2: " << n2 << "\n";  

    cout << "Change reflected in n2: " << n2 << "\n";  

  

    // Call-by-Reference with Reference Arguments  

    int n3 = 8;  

    cout << "address of n3 in main(): " << &n3 << "\n";  

    square3(n3);  

    cout << "Square of n3: " << n3 << "\n";  

    cout << "Change reflected in n3: " << n3 << "\n";  

}  

// Main program  

int main() { example(); }

Output:

Output

address of n1 in main(): 0x7ffd90fcf5ec

Square of n1: address of n1 in square1(): 0x7ffd90fcf5cc

64

No change in n1: 8

address of n2 in main(): 0x7ffd90fcf5f0

address of n2 in square2(): 0x7ffd90fcf5f0

Square of n2: 64

Change reflected in n2: 64

address of n3 in main(): 0x7ffd90fcf5f4

address of n3 in square3(): 0x7ffd90fcf5f4

Square of n3: 64

Change reflected in n3: 64

Explanation:

In this instance, we examine pass-by-value, pass-by-pointer, and pass-by-reference in C++. It demonstrates that when using pass-by-value (square1), alterations made do not impact the initial variable. Conversely, both pass-by-pointer (square2) and pass-by-reference (square3) allow the function to alter the original value, as evidenced by corresponding memory locations and revised outcomes.

Advantage of pointer

Several advantages of pointer in C++ are as follows:

  • Pointer reduces the code and improves the performance, and it is used to retrieve strings, trees, etc. and used with arrays, structures and functions.
  • We can return multiple values from a function using a pointer.
  • It allows us to access any memory location in the computer's memory.
  • Usage of pointer

There are numerous applications of pointers in the C++ programming language. Several examples include:

1) Dynamic memory allocation

In the C++ programming language, memory allocation can be dynamically performed through the malloc and calloc functions, utilizing a pointer for this purpose.

2) Arrays, Functions and Structures

Pointers are extensively utilized in C++ for arrays, functions, and structures, effectively minimizing code length and enhancing program efficiency.

3) Implementing Data Structure

In C++, pointers are essential for constructing intricate data structures such as linked lists, trees, and graphs. They enable dynamic allocation and connection of elements.

C++ Pointer FAQs

1) What is a pointer in C++?

In C++, a pointer is a variable that is also referred to as a locator or indicator, directing to the memory location of a value. It allows for direct access and modification of data stored at that specific address.

2) How do we declare a pointer in C++?

A pointer can be declared using the (*) operator.

Example:

Example

int *ptr

3) What does the & symbol mean in C++?

In C++, the & symbol is used to store the memory address of a variable.

4) What does it mean by dereferencing a pointer in C++?

In C++, dereferencing involves retrieving the value stored at a specific memory location.

For example:

Example

cout << *ptr;

5) What is a NULL pointer in C++?

In C++, a null pointer is a pointer assigned the value nullptr (or NULL) and does not point to any valid memory location.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience