🔗 C++ Pointers and Arrays – One Name, Many Values
In C++, arrays and pointers are best buddies. An array name acts like a pointer to its first element! 🧠
This makes it easy to access or loop through arrays using pointer logic.
📘 Quick Facts
arr
is a pointer to the first element*(arr + i)
is the same asarr[i]
- Pointer arithmetic helps move through the array
🔧 Example: Access Array Elements Using Pointer
#include <iostream> using namespace std; int main() { int numbers[5] = {10, 20, 30, 40, 50}; int* ptr = numbers; // Points to first element for (int i = 0; i < 5; i++) { cout << "Element " << i << ": " << *(ptr + i) << endl; } return 0; }
🔁 Example: Use Pointer as Loop Variable
Let’s walk through the array using a pointer directly.
#include <iostream> using namespace std; int main() { int data[] = {1, 2, 3, 4}; int* p = data; while (p < data + 4) { cout << *p << " "; p++; } return 0; }
💡 Summary
- Array name is a pointer to the first element
arr[i]
=*(arr + i)
- Pointers make array navigation flexible
Now you can loop, access, and play with arrays like a pointer pro! 🧩