C++ Pointer Arithmetic

🚀 C++ Pointer Arithmetic – Move Around Like a Pro

In C++, pointers are not just static — they can move around memory using arithmetic! 🧭

This is super useful when working with arrays or dynamic memory.

🧮 What You Can Do with Pointer Arithmetic

  • ptr + n – jump ahead by n positions
  • ptr - n – go back by n positions
  • ++ptr / --ptr – move to next/previous item
  • ptr1 - ptr2 – get distance between two pointers

🔧 Example: Walk Through an Array Using a Pointer

#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int* ptr = numbers;  // Points to first element

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

    return 0;
}

Try It Now

🔄 Example: Using ++ to Move the Pointer

This is like marching forward through memory!

#include <iostream>
using namespace std;

int main() {
    int nums[] = {5, 10, 15};
    int* p = nums;

    cout << *p << endl;  // 5
    p++;
    cout << *p << endl;  // 10
    p++;
    cout << *p << endl;  // 15

    return 0;
}

Try It Now

💡 Summary

  • You can add or subtract numbers with pointers
  • Pointer arithmetic makes array access super flexible
  • But be careful — going out of bounds is dangerous! ⚠️

With pointer arithmetic, you’re not just storing memory — you’re navigating it! 🧭