The Wayback Machine - https://web.archive.org/web/20240930181226/https://www.geeksforgeeks.org/cpp-pointer-arithmetic/
Open In App

C++ Pointer Arithmetic

Last Updated : 01 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, pointer variables are used to store the addresses of other variables, functions, structures, and even other pointers and we can use these pointers to access and manipulate the data stored at that address.

Pointer arithmetic means performing arithmetic operations on pointers. It refers to the operations that are valid to perform on pointers. Following are the arithmetic operations valid on pointers in C++:

  1. Incrementing and Decrementing Pointers
  2. Addition of Constant to Pointers
  3. Subtraction of Constant from Pointers
  4. Subtraction of Two Pointers of the Same Type
  5. Comparison of Pointers

We will explore all the operations listed above in detail with examples.

Prerequisite: To understand pointer arithmetic in C++, we should know Pointers in C++.

1. Incrementing and Decrementing Pointer in C++

Incrementing or decrementing a pointer will make it refer to the address of the next or previous data in the memory. This process differs from incrementing and decrementing numeric data. 

For example, when we increment or decrement a numeric data, its value is incremented or decremented by 1. However, incrementing or decrementing a pointer, instead of increasing or decreasing by 1, the address increases or decreases by 1 multiplied by the size of the data type it is pointing to. (one of the reasons why the pointer declaration requires the information about the type of data it is pointing to)

Incrementing a Pointer

Incrementing a pointer will depend on the type of variable address stored in the pointer. If the pointer stored the address of the integer type variable then the size of the integer pointer can be 4 or 8 bytes depending upon the 32-bit machine or 64-bit machine respectively. So, now if we increment an integer type variable it will be incremented by 4 bytes or 8 bytes depending upon its size.

For example, If a pointer holds the address 1000 and we increment the pointer, then the pointer will be incremented by 4 or 8 bytes (size of the integer), and the pointer will now hold the address 1004.

Decrementing a Pointer

When we apply a decrement operation on the pointer then the pointer is decremented by 4 or 8 bytes depending upon the machine.

For example, If a pointer holds the address 1004 and we decrement the pointer, then the pointer will be decremented by 4 or 8 bytes (size of the integer), and the pointer will now hold the address 1000.

Pointer-Increment-Decrement-in-C++

Example of Pointer Increment and Decrement

The below C++ program demonstrates the increment and decrement of a pointer.

C++
// CPP program to demonstrate the incrementy and decrement
// of a pointer
#include <iostream>
using namespace std;

int main()
{

    int num = 27;
    // Storing address of num in num_pointer
    int* num_pointer = &num;

    // Print size of int
    cout << "Size of int: " << sizeof(int) << endl;

    // Print the address stored at num_pointer
    cout << "Before Increment: " << num_pointer << endl;
    // Increment pointer
    num_pointer++;

    cout << "After Increment: " << num_pointer << endl;

    // Print the address stored at num_pointer
    cout << "Before Decrement: " << num_pointer << endl;
    // Decrement pointer
    num_pointer--;

    cout << "After Decrement: " << num_pointer << endl;

    return 0;
}

Output
Size of int: 4
Before Increment: 0x7ffe3e7f56d4
After Increment: 0x7ffe3e7f56d8
Before Decrement: 0x7ffe3e7f56d8
After Decrement: 0x7ffe3e7f56d4

Explanation

We have subtracted ‘1’ from pointer ptr which stored the address of variable ‘num’. While subtraction firstly ‘1’ is multiplied by the size of the integer which is 4 bytes and then subtracted from the pointer.

In the same way, this will be applicable to other data types such as float, double, char, etc.

Refer to the article to learn how to access elements of an array using pointers.

2. Addition of Constant to Pointers

We can add integer values to Pointers and the pointer is adjusted based on the size of the data type it points to. For example, if an integer pointer stores the address 1000 and we add the value 5 to the pointer, it will store the new address as:

1000 + (5 * 4(size of an integer)) = 1020

Pointer-Addition-in-C++

Example

The below C++ code demonstrates the addition of a constant to a pointer.

C++
// CPP program to demonstrate the addition of a constant to
// a pointer
#include <iostream>
using namespace std;

int main()
{

    int num = 20;
    int* ptr = &num;

    cout << "Address stored in ptr: " << ptr << endl;

    // Adding the integer value 1 to the pointer ptr
    ptr = ptr + 1;
    cout << "Adding 1 to ptr: " << ptr << endl;

    // Adding the integer value 2 to the pointer ptr
    ptr = ptr + 2;
    cout << "Adding 2 to ptr: " << ptr << endl;

    return 0;
}

Output
Address stored in ptr: 0x7ffdb8634a94
Adding 1 to ptr: 0x7ffdb8634a98
Adding 2 to ptr: 0x7ffdb8634aa0

Explanation

We have initialized a variable of integer type and then initialized a pointer ‘ptr’ of integer type with an address of a variable ‘num’. Now, we print the address stored in pointer ‘ptr’ after that we have added ‘1’ to ptr and then again print the address stored in ptr. Now we can see in the output that the ‘4’ is added to ptr instead of ‘1’. This is because when we add any constant to the pointer, it first multiplies it to the size of the type of pointer which is ‘integer’ in this case and here it takes 4 bytes. so, it first multiplies ‘1’ with ‘4’ and then adds the (1*4) to the pointer. The same will happen when we add 2, (2*4) will be added to the pointer ‘ptr’.

3. Subtraction of Constant from Pointers

We can also subtract a constant from Pointers and it is the same as the addition of a constant to a pointer. For example, if an integer pointer stores the address 1000 and we subtract the value 5 from the pointer, it will store the new address as:

1000 - (5 * 4(size of an integer)) = 980

Pointer-Subtraction-in-C++

Example

The below C++ code demonstrates the Subtraction of a constant from a pointer.

C++
// CPP program to demonstrate the subtraction of a constant
// from a pointer
#include <iostream>
using namespace std;

int main()
{

    int num = 100;

    int* ptr = &num;

    cout << "Address stored in ptr: " << ptr << endl;

    // Subtracting the integer value 1 from pointer ptr
    ptr = ptr - 1;
    cout << "Subtract 1 from ptr: " << ptr << endl;

    return 0;
}

4. Subtraction of Two Pointers of the Same Datatype

The Subtraction of two pointers can be done only when both pointers are of the same data type. The subtraction of two pointers gives the number of elements present between the two pointers.

Example

The below C++ code demonstrates the subtraction of two pointers.

C++
// CPP program to demonstrate the subtraction of two
// pointers
#include <iostream>
using namespace std;

int main()
{

    int num = 45;

    int* ptr1 = &num;

    // Adding 4 to ptr1 and stored in ptr2
    int* ptr2 = ptr1 + 4;

    cout << "Address stored in ptr1:" << ptr1 << endl;
    cout << "Address stored in ptr2:" << ptr2 << endl;

    // Subtracting ptr2 from ptr1
    cout << "ptr2 - ptr1 = " << ptr2 - ptr1 << endl;

    return 0;
}

Output
Address stored in ptr1:0x7ffdd3f5673c
Address stored in ptr2:0x7ffdd3f5674c
ptr2 - ptr1 = 4

5. Comparison of Pointers

In C++, we can perform a comparison between the two pointers using the relational operators(>, <, >=, <=, ==, !=). We generally use this operation to check whether the two-pointer as pointing to the same memory location or not.

Example: Comparing Pointer Variables

C++
// C++ Program to illustrate the pointer comparison
#include <iostream>
using namespace std;

int main()
{
    // declaring some pointers
    int num = 10;
    int* ptr1 = &num;
    int** ptr2 = &ptr1;
    int* ptr3 = *ptr2;

    // comparing equality
    if (ptr1 == ptr3) {
        cout << "Both point to same memory location";
    }
    else {
        cout << "ptr1 points to: " << ptr1 << endl;
        cout << "ptr3 points to: " << ptr3 << endl;
    }
    return 0;
}

Output
Both point to same memory location

Comparison to NULL

We can compare the pointer of a type to NULL. This operation helps us to find whether the given pointer points to some memory address or not. It helps us to control errors such as segmentation faults.

Example

C++
// C++ program to compare the pointer to NULL
#include <iostream>
using namespace std;

int main()
{
    int num = 10;
    // assigning null in case we dont use pointer
    int* ptr = NULL;
    ptr = &num;

    // checking if the pointer is in use or not
    if (ptr == NULL) {
        cout << "No value is pointed";
    }
    else {
        cout << "The value pointed is " << *ptr;
    }
    return 0;
}

Output
The value pointed is 10

Note: It is recommend that we should initialize new pointer variables with NULL so that we can make check if the pointer is assigned some meaningful value.

Related Articles



Similar Reads

C++ Pointer To Pointer (Double Pointer)
In C++ a Pointer is a variable that is used to store the memory address of other variables. It is a variable that points to a data type (like int or string) of the same type and is created with the * operator. Syntax of a Pointer in C++: data_type_of_pointer *name_of_variable = & normal_variable; What is a Pointer to a Pointer or Double Pointer
4 min read
Pointer to an Array | Array Pointer
Prerequisite: Pointers Introduction  Consider the following program:  [GFGTABS] C #include<stdio.h> int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf("%p\n", ptr); return 0; } [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer
9 min read
Sum of array using pointer arithmetic
Given an array, write a program to find the sum of array using pointers arithmetic. In this program we make use of * operator . The * (asterisk) operator denotes the value of variable. The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer . sum() functi
2 min read
Multidimensional Pointer Arithmetic in C/C++
In C/C++, arrays and pointers have similar semantics, except on type information. As an example, given a 3D array int buffer[5][7][6]; An element at location [2][1][2] can be accessed as "buffer[2][1][2]" or *( *( *(buffer + 2) + 1) + 2). Observe the following declaration T *p; // p is a pointer to an object of type T When a pointer p is pointing t
4 min read
Pointer vs Array in C
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2. the & operator array is an alias for &array[0
1 min read
Type of 'this' Pointer in C++
In C++, this pointer refers to the current object of the class and passes it as a parameter to another method. 'this pointer' is passed as a hidden argument to all non-static member function calls. Type of 'this' pointer The type of this depends upon function declaration. The type of this pointer is either const ExampleClass * or ExampleClass *. It
2 min read
How to write C functions that modify head pointer of a Linked List?
Consider simple representation (without any dummy node) of Linked List. Functions that operate on such Linked lists can be divided into two categories: 1) Functions that do not modify the head pointer: Examples of such functions include, printing a linked list, updating data members of nodes like adding given a value to all nodes, or some other ope
4 min read
Jump Pointer Algorithm
The Jump pointer algorithm is a design technique for parallel algorithms that operate on pointer structures, such as arrays or linked list. This algorithm is normally used to determine the root of the forest of a rooted tree. In the jump pointer algorithm, we pre-process a tree so that one can able to answer the queries to find any parent of any no
15+ min read
Common Memory/Pointer Related bug in C Programs
Dereferencing an unknown memory location : C programmers mostly use scanf() function to take input, but sometimes a small mistake can bring a bug or even crash whole program. The syntax for scanf() is scanf("%d", &a);. It might be possible to miss a & and write &a as a so now scanf("%d", a); is dereferencing to an unknown location. Now
6 min read
C++ Program to count Vowels in a string using Pointer
Pre-requisite: Pointers in C++ Given a string of lowercase english alphabets. The task is to count number of vowels present in a string using pointers Examples: Input : str = "geeks" Output : 2 Input : str = "geeksforgeeks" Output : 5 Approach: Initialize the string using a character array. Create a character pointer and initialize it with the firs
2 min read
Trie Data Structure using smart pointer and OOP in C++
We will implement trie using smart pointers in C++ and OOP. Here, We have already discussed the implementation of trie data using recursionIn our implementation node of a trie look like : C/C++ Code class TrieNode{ public: // Use of shared_ptr for storing Children // Pointers of TrieNode shared_ptr children[ALPHABET_SIZE]; // Tracks whether If this
6 min read
C++ Pointer Operators
Prerequisite: Pointers in C++ A pointer variable is a variable that stores the address of another variable or in other a pointer variable points to the variable whose address is stored inside it. Syntax: int *pointer_name; There are mainly two types of Pointer operators mainly used: Address of operator (&)The indirection operator/Dereference op
2 min read
C++ - Pointer to Structure
Pointer to structure in C++ can also be referred to as Structure Pointer. A structure Pointer in C++ is defined as the pointer which points to the address of the memory block that stores a structure. Below is an example of the same: Syntax: struct name_of_structure *ptr; // Initialization of structure is done as shown below ptr = &structure_var
2 min read
C++ Function Call By Pointer
Several ways exist in which data (or variables) could be sent as an argument to a function. Two of the common ones are Passing by Value and Passing by Reference. Example: C/C++ Code // C++ Program to demonstrate // Pass by value and // Pass by reference #include <iostream> using namespace std; // Pass by reference void swap(int& x, int
3 min read
Function Pointer in C++
Prerequisites: Pointers in C++Function in C++ Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of pointers. The address of the variable you’re working wi
4 min read
Dereference Pointer in C
We know that the pointer variable can store the memory address in C language and in this article, we will learn how to use that pointer to access the data stored in the memory location pointed by the pointer. What is a Pointer? First of all, we revise what is a pointer. A pointer is a variable that stores the memory address of another variable. The
4 min read
Declare a C/C++ function returning pointer to array of integer pointers
Declare "a function with argument of int* which returns pointer to an array of 4 integer pointers". At the first glance it may look complex, we can declare the required function with a series of decomposed statements. 1. We need, a function with argument int *, function(int *) 2. a function with argument int *, returning pointer to (*function(int *
2 min read
Scope Resolution Operator vs this pointer in C++
Scope resolution operator is for accessing static or class members and this pointer is for accessing object members when there is a local variable with the same name. Consider below C++ program: C/C++ Code // C++ program to show that local parameters hide // class members #include <iostream> using namespace std; class Test { int a; public: Te
3 min read
Opaque Pointer in C++
Opaque as the name suggests is something we can't see through. e.g. wood is opaque. An opaque pointer is a pointer that points to a data structure whose contents are not exposed at the time of its definition. The following pointer is opaque. One can't know the data contained in STest structure by looking at the definition. struct STest* pSTest; It
6 min read
Passing By Pointer vs Passing By Reference in C++
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++? Let's first understand what Passing by Pointer and Passing by Reference in C++ mean: Passing by Pointer Here, the memory location (address) of
5 min read
A C/C++ Pointer Puzzle
Prerequisite: Pointers Assuming the size of int = 4 bytes, size of a pointer variable = 8 byte, what will be the output of following program. Few hints on how to solve it: Size of int = 4 bytes, size of a pointer variable = 8 bytes (on my machine), adding 1 to a pointer makes the pointer point to its next immediate type a is of type int (*)[5][6] a
2 min read
Delete multiple occurrences of key in Linked list using double pointer
Given a singly linked list, delete all occurrences of a given key in it. For example, consider the following list. Input: 2 -> 2 -> 4 -> 3 -> 2 Key to delete = 2Output: 4 -> 3 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.This is mainly an alternative of this post which deletes multiple occurrence
6 min read
Application of Pointer in C++
A pointer is a variable that stores the memory address as its value. It points to the location in the computer's memory where the actual data is stored. Pointer is one of the core features of the C++ programming language which enables various functions like dynamic memory allocation, pass-by-reference, etc. In this article, we will look at some maj
8 min read
void Pointer in C++
In C++, a void pointer is a pointer that is declared using the 'void' keyword (void*). It is different from regular pointers it is used to point to data of no specified data type. It can point to any type of data so it is also called a "Generic Pointer". Syntax of Void Pointer in C++void* ptr_name; As the type of data the void pointer is pointing t
7 min read
When Do We Pass Arguments by Reference or Pointer in C++?
In C++, we can pass arguments to a function as a value, reference (or pointer). Each method has its unique benefits and uses. In this article, we will discuss the application or cases where we should pass the arguments by reference or a pointer. But first, let’s quickly revisit the definitions of pointers and references. Pointers in C++ Pointers ar
4 min read
Pointer to an Array in C++
Pointers in C++ are variables that store the address of another variable while arrays are the data structure that stores the data in contiguous memory locations. In C++, we can manipulate arrays by using pointers to them. These kinds of pointers that point to the arrays are called array pointers or pointers to arrays. In this article, we will discu
6 min read
NULL Pointer in C++
A NULL Pointer in C++ indicates the absence of a valid memory address in C++. It tells that the pointer is not pointing to any valid memory location In other words, it has the value "NULL" (or 'nullptr' since C++11). This is generally done at the time of variable declaration to check whether the pointer points to some valid memory address or not. I
4 min read
Function Pointer in C
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer. [GFGTABS] C++ #include <stdio.h> // A normal function with an int parameter // and void return type void fun(int a) { printf("Value of a is %d\n", a);
6 min read
How to Get std::vector Pointer to Raw Data in C++?
In C++, std::vector is a dynamic array that stores the data in the contiguous memory allocated during runtime. It internally keeps the pointer to this raw data memory. In this article, we will learn how to get std::vector pointer to the raw data. Methods to Get Pointer to Raw Data in std::vectorIn C++, there are two ways to find the pointer to the
3 min read
How to Specify a Pointer to an Overloaded Function?
In C++, function overloading allows multiple functions to have the same name but different parameter lists. While overloading is a powerful feature, it can lead to ambiguity when trying to assign a pointer to one of these overloaded functions. To resolve this ambiguity, specific methods can be used to correctly specify a pointer to the desired over
4 min read
Article Tags :
Practice Tags :