🚀 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 bynpositionsptr - n– go back bynpositions++ptr/--ptr– move to next/previous itemptr1 - 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;
}
🔄 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;
}
💡 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! 🧭