1. Home
C++ Tutorial

Explore C++ Tutorials: Exploring the World of C++ Programming

Discover comprehensive C++ tutorials designed for beginners and advanced programmers alike. Enhance your coding skills with step-by-step guides and practical examples.

  • 77 Lessons
  • 15 Hours
right-top-arrow
7

Pointer in C++: A Comprehensive Guide

Updated on 19/09/2024425 Views

Pointers are our compass and map in C++ programming, guiding us through the various computer memory structures. They are the keys that unlock the ability to manipulate data directly at its source, offering a level of control and flexibility that few other programming concepts can match. 

In this tutorial, I will cover what pointers are and we will explore how to declare, initialize, and manipulate them. We'll also look at techniques for safely using pointers to avoid common pitfalls, allowing you to harness the concept of a pointer in C++ while ensuring the robustness and reliability of your C++ code.

What is a Pointer in C++?

At their core, pointers are simply variables, but with a twist. Instead of storing data directly, a CPP pointer holds the memory address of another variable. We can think of memory as a vast city with each byte representing a unique house. A pointer is like the address of a particular house, telling us precisely where to find it.

Or, we can also think of pointers as signposts on a winding road. Each signpost points to a specific location, directing us towards our destination. Similarly, a pointer in C++ tells us where a particular piece of data resides in memory.

It is crucial to distinguish between the pointer itself (the signpost) and the value it points to (the destination). The pointer variable holds the address, while the value at that address is the actual data we are interested in.

Why Use a Pointer in C++? 

Pointers play a vital role in several key areas of C++ programming:

  • Dynamic Memory Allocation: Pointers allow us to allocate memory on the fly during program execution, giving us the flexibility to create and manage data structures of varying sizes.
  • Indirect Access and Modification: Pointers allow us to access and modify variables indirectly, which is useful in situations where direct access might be restricted or cumbersome.
  • Passing Arguments by Reference: By passing a pointer to a function, we allow the function to modify the original data, avoiding the overhead of copying large objects.

Pointers are also deeply intertwined with arrays and strings in C++. An array name can decay into a pointer to its first element, while strings are often represented as arrays of characters, manipulated through pointers. Additionally, a C++ function pointer enables us to store the address of a function, allowing for dynamic function calls and callbacks.

Precautionary Advice for Using a Pointer in C++

While pointers are powerful, they demand respect and caution. Misusing pointers can lead to dire consequences:

  • Dangling Pointers: These are pointers that point to memory locations that have been deallocated or are no longer valid. Dereferencing a dangling pointer can lead to crashes or unpredictable behavior.
  • Memory Leaks: Failing to deallocate memory that we have allocated with pointers can lead to memory leaks, where our program consumes more and more memory over time, eventually exhausting available resources.

Understanding Memory Addresses

To grasp the concept of pointers fully, we must first venture into the fundamental building blocks of computer memory. Understanding how memory is organized and how variables reside within it is essential for comprehending the role of pointers.

Memory Basics

At its most fundamental level, computer memory is a vast expanse of individual units called bytes. Each byte is like a tiny container that can hold a single character, a small number, or a part of a larger piece of data. What makes these bytes truly special is that each one has a unique address, much like houses in an area that have unique addresses.

These memory addresses are simply numbers that identify the specific location of each byte in memory. They are essential for the computer to keep track of where data is stored and how to retrieve it.

Variables and Their Addresses

When we declare a variable in our C++ program, the computer allocates a specific portion of memory to store that variable's value. This memory location has an address, and we can think of the variable as residing at that address.

For example, consider the following declaration:

int age = 30;

In this case, the computer sets aside a few bytes in memory to store the integer value 30. The variable age acts as a convenient label for us to refer to this memory location, but under the hood, it is simply an address where the value 30 is stored.

The Address-of Operator (&)

To uncover the memory address of a variable, C++ provides the address-of operator (&). When placed before a variable's name, it returns the memory address where the variable's value is stored.

Example:

int age = 30;

std::cout << &age << std::endl;  // Prints the memory address of the variable age

Storing Addresses in Pointers

Pointers come into play when we want to store these memory addresses for later use.

Example:

int age = 30;

int* agePtr = &age;  // agePtr now stores the address of the age variable

In this pointer in C++ example, agePtr is a pointer variable of type int*, meaning it can hold the address of an integer variable. The &age expression retrieves the address of the age variable and assigns it to agePtr. Now, agePtr acts as a signpost, pointing to the location in memory where the value 30 is stored.

Declaring and Initializing A Pointer in C++

Creating and setting up pointers is the initial stride in your journey through the world of memory manipulation. Let us break down the syntax and initialization.

Syntax

Declaring a pointer in C++ follows a specific pattern:

dataType* pointerName;

Here's what each part of the C++ declare pointer syntax signifies:

  • dataType: The type of data the pointer will point to (e.g., int, char, float). This determines how the pointer interacts with memory.
  • *: The asterisk is the defining characteristic of a pointer declaration. It signifies that the variable is a pointer, holding a memory address rather than the actual data.
  • pointerName: A descriptive name you choose for the pointer variable.

Initializing a Pointer in C++

Before we can use a pointer safely, we must initialize it. Leaving a pointer uninitialized is like having a compass without a direction, it could point anywhere, leading to unpredictable and potentially disastrous consequences.

The most common way to initialize a pointer is to assign it the address of an existing variable using the address-of operator (&).

Example:

int number = 42;

int* numberPtr = &number;  // numberPtr now points to the memory location of number

Alternatively, we can initialize a pointer to nullptr. This special value indicates that the pointer is not currently pointing to any valid memory location.

Example:

int* ptr = nullptr; 

If you wish to learn how to code in C++, you can check out upGrad’s software engineering courses.

Types of Pointers in C++

C++ offers a rich variety of pointer types, each designed to interact with specific data types in memory. Understanding these different types is crucial for leveraging the full potential of pointers in your code.

Here are the fundamental data type pointers (the most common types):

  • int*: Points to an integer.
  • char*: Points to a character (often used for C-style strings).
  • double*: The C++ double pointer points to a double-precision floating-point number.
  • float*: Points to a single-precision floating-point number.

Pointer Arithmetic

One of the unique features of pointers is the ability to perform arithmetic operations on them. However, pointer arithmetic is not your ordinary addition or subtraction. When we add 1 to a pointer, we are not adding 1 to the address itself, we are moving the pointer to the next memory location of the type it points to.

Example:

int numbers[] = {10, 20, 30};

int* ptr = numbers;  // Points to the first element (10)

std::cout << *ptr << std::endl; // Output: 10

++ptr;  // Now points to the second element (20)

std::cout << *ptr << std::endl; // Output: 20

void* Pointers (Generic Pointers)

A void pointer can hold the address of any data type. It is essentially a "generic" pointer, requiring explicit casting to be dereferenced.

Example:

int num = 42;

void* voidPtr = &num;

int* intPtr = static_cast<int*>(voidPtr); // Cast back to int*

std::cout << *intPtr << std::endl;        // Output: 42

const Pointers

A const pointer C++ cannot be used to modify the value it points to, but the pointer itself can be changed to point to a different location. It is useful for protecting data from accidental modification.

Example:

int value = 10;

const int* ptr = &value;

*ptr = 20;  // Error! Cannot modify the value through a const pointer

ptr++;       // Valid! Can change where the pointer points

Pointers to const Data

These pointers can point to const data but can be modified to point elsewhere.

Example:

const int value = 10;

int* const ptr = &value; 

ptr++;       // Error! Cannot change where the pointer points

*ptr = 20;  // Error! Cannot modify const data 

Class Pointers

A C++ class pointer is a variable that stores the memory address of a class object. It allows us to indirectly access and manipulate the members (data and functions) of the object it points to.

Example:

MyClass obj;

MyClass* ptr = &obj;  // ptr now points to obj

Pointers to Functions

These pointers hold the address of a function, allowing us to call functions indirectly and pass them as arguments to other functions.

Example:

int add(int a, int b) {

    return a + b;

}

int (*funcPtr)(int, int) = add;

std::cout << funcPtr(5, 3) << std::endl; // Output: 8

Smart Pointers

A C++ smart pointer is an object that acts like a pointer but provides automatic memory management. They wrap a raw pointer and take care of deallocating the memory when it is no longer needed, preventing memory leaks and dangling pointers.

Example (unique_ptr):

std::unique_ptr<int> ptr(new int(42)); // ptr owns the integer

Example (shared_ptr):

std::shared_ptr<int> ptr1(new int(42));

std::shared_ptr<int> ptr2 = ptr1; // Both ptr1 and ptr2 share ownership

Example of Pointers in C++ Program

Here is a C++ pointer program that you can try out yourself:

C++ pointer program example

Code:

#include <iostream>

void swap(int* a, int* b) {

    int temp = *a; 

    *a = *b;

    *b = temp;

}

int main() {

    int x = 5, y = 10;

    std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;

    swap(&x, &y); // Pass addresses of x and y

    std::cout << "After swap: x = " << x << ", y = " << y << std::endl;

    return 0;

}

In this C++ pointer example, we use the swap() function to take the pointers to two integers. The program uses dereferencing to access and modify the values at those memory locations, effectively swapping them. In the main() function, we declare and initialize x and y. We then pass their addresses to the swap function. After the function call, x and y are swapped.

Final Tips

Pointers are not just variables, they are gateways to specific memory locations, storing addresses that lead to your data. Arrays and pointers are closely intertwined, with array names often decaying into pointers. This enables seamless array traversal and manipulation using pointer arithmetic.

Also, by passing data by reference instead of copying it, you can significantly improve the performance of your functions, especially when dealing with large data structures. A pointer in C++ enables the creation of dynamic data structures like linked lists, trees, and graphs, which are essential for various algorithms and applications. Pointers allow us to directly access and manipulate memory-mapped hardware devices, essential in low-level programming and embedded systems.

If you wish to learn programming languages such as C++, you can check out upGrad’s computer science programs such as the Master’s in Computer Science Program.

Frequently Asked Questions

  1. What is a pointer in C++?

A pointer in C++ is a variable that can store the memory addresses of other variables. Pointers act like signposts, pointing to the location of data in memory.

  1. How do you declare a pointer?

You declare a pointer by specifying the data type it points to followed by an asterisk (*) and the pointer name: int* ptr; (pointer to an integer).

  1. How do you initialize a pointer?

You initialize a pointer by assigning it the address of an existing variable using the address-of operator (&): int x = 5; int* ptr = &x; or by setting it to nullptr to indicate it doesn't point to anything.

  1. How do you access the value pointed to by a pointer?

Use the dereference operator (*): int value = *ptr; (assigns the value stored at the address in ptr to the variable value).

  1. What is pointer arithmetic?

Pointer arithmetic involves adding or subtracting integer values to/from pointers, effectively moving them to different memory locations based on the size of the data type they point to.

  1. What is a pointer to a pointer?

A pointer to a pointer is a pointer variable that stores the memory address of another pointer variable. It's declared using two asterisks: int x = 5; int* ptr1 = &x; int** ptr2 = &ptr1;

Kechit Goyal

Kechit Goyal

Team Player and a Leader with a demonstrated history of working in startups. Strong engineering professional with a Bachelor of Technology (BTech…Read More

Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...