Pointer Arithmetic

Pointer arithmetic in C++ involves performing arithmetic operations on pointers to navigate through memory and access data. When a pointer points to an element in an array or a memory block, arithmetic operations such as addition, subtraction, increment, and decrement can be applied to the pointer to move it to different memory locations. Pointer arithmetic is particularly useful for iterating over arrays, accessing elements sequentially, and dynamically allocating memory.

Pointer arithmetic in C++ is based on the size of the data type the pointer points to. When adding or subtracting an integer value from a pointer, the size of the data type is automatically taken into account. For example, if a pointer points to an integer variable, incrementing the pointer by 1 will move it to the next integer-sized memory location.

When you perform arithmetic operations on pointers, the compiler adjusts the pointer’s address based on the size of the data type it points to. For example, incrementing a pointer to an integer moves its address by the size of an integer (typically 4 bytes on a 32-bit system). Similarly, decrementing a pointer to a character moves its address by 1 byte.

Pointer arithmetic is extensively used in scenarios where direct memory manipulation or traversal of arrays is required. Here are some essential concepts and operations related to pointer arithmetic:

Pointer Arithmetic Operations:

  • Addition: ptr = ptr + offset
  • Subtraction: ptr = ptr - offset
  • Increment: ptr++ or ++ptr
  • Decrement: ptr-- or --ptr

Traversal of Arrays:

  • Pointer arithmetic allows iterating through arrays efficiently without using array indices.

Memory Allocation and Deallocation:

  • Pointers facilitate dynamic memory allocation using new and deallocation using delete.

Pointer Arithmetic with Arrays:

  • You can use pointer arithmetic to access elements of arrays directly using pointers.

Pointer Arithmetic with Structs and Objects:

  • Pointers can be used to navigate through members of structs and objects.

Basic Pointer Arithmetic

#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *ptr = arr;

    cout << "Element at index 2: " << *(ptr + 2) << endl;
    
    return 0;
}

Here, pointer ptr is incremented by 2 (equivalent to moving two integer sizes) to access the element at index 2 of the array.

Traversal of Array using Pointer Arithmetic

#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int *ptr = arr;

    for (int i = 0; i < 5; i++) {
        cout << *(ptr + i) << " ";
    }
    
    return 0;
}

This example demonstrates how to traverse through the array using pointer arithmetic instead of array indices.

Increment and Decrement Operations

#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int *ptr = arr;

    cout << "Initial: " << *ptr << endl;
    ptr++;
    cout << "After increment: " << *ptr << endl;
    ptr--;
    cout << "After decrement: " << *ptr << endl;
    
    return 0;
}

If the pointer pointing to array of objects of a class is incremented, it will automatically point to the next object of the class which is the next array element

The following example demonstrates traversing an array of objects of a class using pointer arithmetic, along with line-by-line explanation:

#include <iostream>

// Define a simple class
class MyClass {
public:
    int value;

    // Constructor
    MyClass(int val) : value(val) {}
};

int main() {
    const int size = 5; // Size of the array
    MyClass array[size]; // Declare an array of MyClass objects

    // Initialize the array with some values
    for (int i = 0; i < size; ++i) {
        array[i] = MyClass(i * 10);
    }

    // Pointer to the beginning of the array
    MyClass* ptr = array;

    // Traverse the array using pointer arithmetic
    for (int i = 0; i < size; ++i) {
        // Accessing the current object using pointer dereferencing
        std::cout << "Element " << i << ": " << ptr->value << std::endl;

        // Move the pointer to the next object in the array
        ptr++;
    }

    return 0;
}

explanation of the code :-

#include <iostream>: Including the necessary header file for input-output operations.

class MyClass { ... };: Defining a simple class named MyClass with a single member variable value.

MyClass(int val) : value(val) {}: Constructor of the MyClass class that initializes the value member.

int main() { ... }: Main function where the program execution starts.

const int size = 5;: Declaring a constant variable size to hold the size of the array.

MyClass array[size];: Declaring an array of MyClass objects with size size.

for (int i = 0; i < size; ++i) { ... }: Initializing the array elements with some values using a loop.

MyClass* ptr = array;: Declaring a pointer ptr of type MyClass and assigning it the address of the first element of the array.

for (int i = 0; i < size; ++i) { ... }: Looping through the array elements.

std::cout << "Element " << i << ": " << ptr->value << std::endl;: Printing the index and value of the current element pointed to by ptr.

ptr++;: Incrementing the pointer to point to the next element in the array.

The code above demonstrates how to traverse an array of objects of a class using pointer arithmetic, where the pointer is incremented to move to the next object in the array.

These examples illustrate the fundamental aspects of pointer arithmetic in C++, including traversal of arrays, memory manipulation, and accessing elements of data structures. Pointer arithmetic offers versatility and efficiency, making it an essential aspect of C++ programming.

Here are some more examples of Pointer Arithmetic in C++

Pointer Arithmetic with Character Array

Introduction: This program demonstrates pointer arithmetic with a character array. It initializes a character array with a string, assigns a pointer to its first element, and then performs various arithmetic operations on the pointer.

#include <iostream>

int main() {
    char str[] = "Hello";
    char *ptr = str; // Pointer pointing to the first character of the array

    std::cout << "String: " << ptr << std::endl; // Output: Hello
    ptr += 2; // Incrementing pointer by 2 (size of char)
    std::cout << "String after adding 2: " << ptr << std::endl; // Output: llo

    return 0;
}

Explanation:

  • char str[] = "Hello";: Declares a character array with the string “Hello”.
  • char *ptr = str;: Declares a pointer ptr and assigns it to the address of the first character of the array.
  • std::cout << "String: " << ptr << std::endl;: Prints the string starting from the memory location pointed to by ptr, which is “Hello”.
  • ptr += 2;: Increments the pointer by 2 (equivalent to moving two characters ahead in the string).
  • std::cout << "String after adding 2: " << ptr << std::endl;: Prints the string starting from the new memory location pointed to by ptr, which is “llo”.

This program demonstrates how pointer arithmetic works with character arrays, allowing us to navigate through strings character by character.

Pointer Arithmetic with Dynamic Memory Allocation

Introduction: This program demonstrates pointer arithmetic with dynamically allocated memory. It dynamically allocates memory for an integer array, assigns a pointer to its first element, and then performs various arithmetic operations on the pointer.

#include <iostream>

int main() {
    int size = 5;
    int *arr = new int[size]; // Dynamically allocate memory for an integer array
    int *ptr = arr; // Pointer pointing to the first element of the array

    for (int i = 0; i < size; ++i) {
        arr[i] = i * 10; // Assigning values to the array elements
    }

    std::cout << "Value at ptr: " << *ptr << std::endl; // Output: 0
    ptr++; // Incrementing pointer by 1 (size of int)
    std::cout << "Value at ptr after increment: " << *ptr << std::endl; // Output: 10
    ptr += 2; // Incrementing pointer by 2 (2 * size of int)
    std::cout << "Value at ptr after adding 2: " << *ptr << std::endl; // Output: 30

    delete[] arr; // Free dynamically allocated memory

    return 0;
}

Explanation:

  • int size = 5;: Specifies the size of the dynamically allocated array.
  • int *arr = new int[size];: Dynamically allocates memory for an integer array of size size.
  • int *ptr = arr;: Declares a pointer ptr and assigns it to the address of the first element of the dynamically allocated array.
  • for (int i = 0; i < size; ++i) { arr[i] = i * 10; }: Assigns values to the dynamically allocated array elements.
  • std::cout << "Value at ptr: " << *ptr << std::endl;: Prints the value at the memory location pointed to by ptr, which is 0.
  • ptr++;: Increments the pointer by 1 (since it’s pointing to an integer array, it moves to the next integer element).
  • std::cout << "Value at ptr after increment: " << *ptr << std::endl;: Prints the value at the new memory location pointed to by ptr, which is 10.
  • ptr += 2;: Increments the pointer by 2 (equivalent to moving two integers ahead in the array).
  • std::cout << "Value at ptr after adding 2: " << *ptr << std::endl;: Prints the value at the new memory location pointed to by ptr, which is 30.

This program illustrates how pointer arithmetic works with dynamically allocated memory, allowing us to navigate through dynamically allocated arrays. Don’t forget to deallocate dynamically allocated memory using delete[] to avoid memory leaks.

Pointer Arithmetic with Structs

Introduction: This program demonstrates pointer arithmetic with structs. It defines a simple struct representing a point with x and y coordinates, dynamically allocates an array of points, assigns a pointer to its first element, and then performs various arithmetic operations on the pointer.

#include <iostream>

struct Point {
    int x;
    int y;
};

int main() {
    int size = 3;
    Point *points = new Point[size]; // Dynamically allocate memory for an array of points
    Point *ptr = points; // Pointer pointing to the first element of the array

    for (int i = 0; i < size; ++i) {
        points[i].x = i;
        points[i].y = i * 2;
    }

    std::cout << "Point at ptr: (" << ptr->x << ", " << ptr->y << ")" << std::endl;
    ptr++; // Incrementing pointer by 1 (size of Point)
    std::cout << "Point at ptr after increment: (" << ptr->x << ", " << ptr->y << ")" << std::endl;

    delete[] points; // Free dynamically allocated memory

    return 0;
}

Explanation:

  • struct Point { int x; int y; };: Defines a struct representing a point with integer x and y coordinates.
  • int size = 3;: Specifies the size of the dynamically allocated array of points.
  • Point *points = new Point[size];: Dynamically allocates memory for an array of points.
  • Point *ptr = points;: Declares a pointer ptr and assigns it to the address of the first element of the dynamically allocated array.
  • for (int i = 0; i < size; ++i) { points[i].x = i; points[i].y = i * 2; }: Assigns values to the x and y coordinates of each point in the array.
  • std::cout << "Point at ptr: (" << ptr->x << ", " << ptr->y << ")" << std::endl;: Prints the coordinates of the point pointed to by ptr.
  • ptr++;: Increments the pointer by 1 (since it’s pointing to a Point struct, it moves to the next Point element).
  • std::cout << "Point at ptr after increment: (" << ptr->x << ", " << ptr->y << ")" << std::endl;: Prints the coordinates of the new point pointed to by ptr.

Explanation:

  • struct Point { int x; int y; };: Defines a struct representing a point with integer x and y coordinates.
  • int size = 3;: Specifies the size of the dynamically allocated array of points.
  • Point *points = new Point[size];: Dynamically allocates memory for an array of points.
  • Point *ptr = points;: Declares a pointer ptr and assigns it to the address of the first element of the dynamically allocated array.
  • for (int i = 0; i < size; ++i) { points[i].x = i; points[i].y = i * 2; }: Assigns values to the x and y coordinates of each point in the array.
  • std::cout << "Point at ptr: (" << ptr->x << ", " << ptr->y << ")" << std::endl;: Prints the coordinates of the point pointed to by ptr.
  • ptr++;: Increments the pointer by 1 (since it’s pointing to a Point struct, it moves to the next Point element).
  • std::cout << "Point at ptr after increment: (" << ptr->x << ", " << ptr->y << ")" << std::endl;: Prints the coordinates of the new point pointed to by ptr.

This program demonstrates how pointer arithmetic works with structs, allowing us to navigate through dynamically allocated arrays of structs.

Pointer Arithmetic with Arrays of Pointers

Introduction: This program demonstrates pointer arithmetic with arrays of pointers. It creates an array of pointers to integers, assigns each pointer to a dynamically allocated integer, and then performs various arithmetic operations on the pointers.

#include <iostream>

int main() {
    const int size = 3;
    int *ptrArray[size]; // Array of pointers to integers

    // Dynamically allocate memory for integers and assign pointers to them
    for (int i = 0; i < size; ++i) {
        ptrArray[i] = new int(i * 10);
    }

    int **ptr = ptrArray; // Pointer to the array of pointers

    std::cout << "Value at ptr: " << **ptr << std::endl; // Output: 0
    ptr++; // Incrementing pointer by 1 (size of int*)
    std::cout << "Value at ptr after increment: " << **ptr << std::endl; // Output: 10

    // Free dynamically allocated memory
    for (int i = 0; i < size; ++i) {
        delete ptrArray[i];
    }

    return 0;
}

Explanation:

  • const int size = 3;: Specifies the size of the array of pointers.
  • int *ptrArray[size];: Declares an array of pointers to integers.
  • for (int i = 0; i < size; ++i) { ptrArray[i] = new int(i * 10); }: Dynamically allocates memory for integers and assigns pointers to them, with values 0, 10, and 20.
  • int **ptr = ptrArray;: Declares a pointer ptr to the array of pointers and assigns it to the address of the first element of the array.
  • std::cout << "Value at ptr: " << **ptr << std::endl;: Prints the value pointed to by the pointer pointed to by ptr, which is 0.
  • ptr++;: Increments the pointer by 1 (since it’s pointing to an array of pointers, it moves to the next pointer element).
  • std::cout << "Value at ptr after increment: " << **ptr << std::endl;: Prints the value pointed to by the new pointer pointed to by ptr, which is 10.

This program demonstrates how pointer arithmetic works with arrays of pointers, allowing us to navigate through arrays of dynamically allocated memory blocks.

These examples should give you a comprehensive understanding of how pointer arithmetic works in C++.