Pointer Arithmetic

Pointer Arithmetic Program in C++

BeginnerTopic: Memory Management Programs
Back

C++ Pointer Arithmetic Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int* ptr = arr;  // Points to first element
    
    cout << "Array elements using pointer arithmetic:" << endl;
    
    // Access elements using pointer
    for (int i = 0; i < 5; i++) {
        cout << "arr[" << i << "] = " << *(ptr + i) << endl;
        cout << "Address: " << (ptr + i) << endl;
    }
    
    cout << "\nIncrementing pointer:" << endl;
    ptr = arr;  // Reset to beginning
    for (int i = 0; i < 5; i++) {
        cout << "Value: " << *ptr << ", Address: " << ptr << endl;
        ptr++;  // Move to next element
    }
    
    cout << "\nDecrementing pointer:" << endl;
    ptr--;  // Now points to last element
    for (int i = 0; i < 5; i++) {
        cout << "Value: " << *ptr << ", Address: " << ptr << endl;
        ptr--;  // Move to previous element
    }
    
    return 0;
}
Output
Array elements using pointer arithmetic:
arr[0] = 10
Address: 0x7fff5fbff6a0
arr[1] = 20
Address: 0x7fff5fbff6a4
arr[2] = 30
Address: 0x7fff5fbff6a8
arr[3] = 40
Address: 0x7fff5fbff6ac
arr[4] = 50
Address: 0x7fff5fbff6b0

Incrementing pointer:
Value: 10, Address: 0x7fff5fbff6a0
Value: 20, Address: 0x7fff5fbff6a4
Value: 30, Address: 0x7fff5fbff6a8
Value: 40, Address: 0x7fff5fbff6ac
Value: 50, Address: 0x7fff5fbff6b0

Decrementing pointer:
Value: 50, Address: 0x7fff5fbff6b0
Value: 40, Address: 0x7fff5fbff6ac
Value: 30, Address: 0x7fff5fbff6a8
Value: 20, Address: 0x7fff5fbff6a4
Value: 10, Address: 0x7fff5fbff6a0

Understanding Pointer Arithmetic

Pointer arithmetic allows you to perform operations on pointers. When you add/subtract integers to/from pointers, the address changes by the size of the data type. For example, ptr + 1 moves to the next element. This is useful for traversing arrays efficiently. Pointer arithmetic respects data type sizes.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents