Jump to content

C++ Pointer Arithmetic


Recommended Posts

This article is about pointer arithmetic in C++. Pointers are variables that store the memory address of the data. Pointer arithmetic is a powerful hallmark in the world of C++ programming language that permits us to deal with different arithmetic operations in which the addition, multiplication, division, increment, decrement, and subtraction involve a pointer to develop the new memory address in our memory buffers. A pointer arithmetic easily creates the dynamic memory allocation. In this C++ article, we will learn how to manipulate the memory address in different ways with the help of pointers and provide proper guidelines and examples.

Scenario 1: Pointer Performs the Increment and Decrement Operations

Here, we will learn about pointer manipulation to produce a different memory addresses that have different purposes. The incrementing and decrementing pointers are also the leverage pointers arithmetic that increase or decrease the address by a factor of one multiplied by the size of the data type to which they are pointing. The code snippet related to this scenario is attached in the following:

#include<iostream>
using namespace std;
const int Arr_Max = 5;
int main () {
   int  var[Arr_Max] = {20, 150, 270};
   int  *ptr; //declare pointer
   ptr = var;
   for (int i = 0; i < Arr_Max; i++) {
      std::cout << "Memory address of the element is : [" << i << "] = ";
     std::cout << ptr << endl;
      cout << "Value against the address is [" << i << "] = ";
      cout << *ptr << endl;
          std::cout<<"pointer incremented successfully"<<endl;
      ptr++;
   }
   std::cout<<"Pointer address before decrement"<<ptr<<endl;
   ptr--;
   std::cout<<"Pointer address after decrement"<<ptr<<endl;
   return 0;
}

 
Here, we define a required library in the code at the very start: “<iostream>”. We define a memory allocation to reserve the space in memory which is “Arr_Max=5”. In the main function, we initialize the array and pass the memory size to that array. Next, the “ptr” pointer declaration is also needed to point out the memory address in memory.

We pass the array to the pointer to access the address. As we all know, arrays always contain multiple items in different locations. So, we needed a loop with the “help” pointer to access every element of an array. Every time the loop executes, we get the memory address and values against this address with the help of the pointer arithmetic “ptr++” increment operator that shifts the memory address to the next address of the memory. The loop execution cycle depends upon the size of an array.  Outside the loop, we want to get the pointer back to the previous memory address by just using the “ptr- -” decrement pointer .

Execute this code by clicking the Execute>Compile & Run option and you will get the following output:

Picture1-9.png
Hopefully, this output is easy to understand. The memory address and value are changed. Shifting the pointer from one location is only possible from the increment pointer arithmetic in C++.

Scenario 2:  Subtracting Two Pointers in C++

In this scenario, we will learn how to subtract two or more pointers in C++. All the arithmetic operations in which the subtraction comes are vital processes as we can only subtract two pointers simultaneously if and only if they have the same data type.

The other operations like addition, multiplication, and division are not possible in the pointer because they make no sense in memory addressing. The code snippet is attached in the following:

#include <iostream>
int main() {
    int Arra[] = {23, 36, 42, 51, 62,77,89,96,100};
    int *ptrr1 = &Arra[3]; // Pointer to the third element (42)
    int *ptrr2 = &Arra[6]; // Pointer to the sixth element (89)
    ptrdiff_t ptrsubtract= ptrr2 - ptrr1;

    std::cout << "Difference between these address is: " << ptrsubtract << " elements" << std::endl;
    return 0;
}

 
The subtraction operation is finding the difference between the memory address in C++. In the main function, we take an array that contains different values at different indexes. In an array, every index has a different memory location. We can only find the difference between two pointers with the help of a pointer arithmetic. Here, we use a special pointer type “ptrdiff_t” that must be used to find the differences between two or more pointers in C++.

The output of this code is attached in the following:

Picture2-8.png
The difference between these addresses is by element vise which is 3.

Scenario 3: Compare Two or More Pointers in C++

In this scenario, we will learn how to compare the different pointers in C++ using different relational operators like “==”, “<=”, “>=”, “<”, ”>”. We can only compare the pointers if they point to the address of elements of the same array. Remember that comparing two pointers with different types can cause undefined behavior. The code snippet that is related to the pointer comparison is mentioned in the following:

#include <iostream>
using namespace std;
int main()
{
    int arr1[10]={4,7,9,11,14,16,18,20,22,25};
    int *ptr1=&arr1[3];
    int *ptr2=&arr1[6];
    int *ptr3=&arr1[8];
    int *ptr4=&arr1[9];
    if(ptr1==ptr2)
    {
        std::cout<<"pointers are equal"<<endl;
    }
    else if(ptr3<=ptr4)
    {
        std::cout<<"ptr3 is less than or equal than ptr4"<<endl;;
    }
    else
    {
        std::cout<<"pointers are not compared at any stage"<<endl;
    }
    return 0;
}

 
Here, we take an array with 10 elements. We declare four pointers that point to a different index of the array. After that, we compare these four pointers at different conditions as seen in the given code. In the “if” condition, check if the “ptr1” pointer is equal to the “ptr2” pointer, and then print the “pointers are equal”. When we have multiple conditions where we use the “else if” condition to check if the “ptr3” pointer is less than equal to the “ptr4” pointer.  After all that, click on the Execute > Compile & Run option.

The output of this code is attached in the following:

Picture3-8.png
It displays a valid condition on the console screen and exits the compilation. The “ptr3” pointer contains a value that is less than or equal to the “ptr4” pointer pointing value.

Scenario 4: Display an Odd number with Pointer Arithmetic

Here, we will see how we can dynamically allocate the memory for an array of an integer. The code snippet related to this case is given in the following:

#include <iostream>
int main() {
    int numbers[] = {1, 12, 33, 24, 15, 776, 71, 18, 29, 50};
    int *ptrr = numbers;
    std::cout << "Odd numbers in the arrays: ";
    for (int i = 0; i < 10; ++i) {
        if (*ptrr % 2 != 0) {
            std::cout << *ptrr << " ";
        }
        ptrr++;
    }
    std::cout << std::endl;
    return 0;
}

 
In the main function, we take an array that contains 10 elements. We need a pointer that points out all the elements in the array to check the odd number in the array. In the “for” loop, check the odd number by dividing the current element of an array. The pointer counter is incremented after checking one element of an array.

After executing the code, the output is displayed on the console screen that is given in the following:

Picture4-5.png
This way, we can display the odd numbers using the pointer arithmetic on the console screen.

Conclusion

We conclude here that the pointer arithmetic is the most effective tool that performs different operations in C++. Make sure that the pointer increments or decreases the value of an array that has the same data type. We can compare the values of an array by their memory addresses with the help of pointer arithmetic in the C++ programming language. We can traverse the array and manage the memory easily with the help of pointer arithmetic.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...