C++ Arrays & Pointers

How Arrays and Pointers Work Together in C++

In C++, an array name is actually a pointer to its first element. That’s why arrays and pointers go hand-in-hand like peanut butter and jelly! 🥪

This connection lets you use pointers to walk through arrays in memory.

🎯 Pointer to First Element

When you write:

int nums[3] = {10, 20, 30};

The name nums holds the address of nums[0]. It’s like saying:

int* ptr = nums;  // Same as &nums[0]

🔧 Example: Access Array with Pointer

#include <iostream>
using namespace std;

int main() {
    int nums[3] = {10, 20, 30};
    int* ptr = nums;

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

    return 0;
}
  

Try It Now

🧠 Pointer Arithmetic

  • ptr + 1 points to the next element
  • *(ptr + i) gives the value at index i
  • This works because memory addresses are handled smartly by the compiler

📌 Same Output, Different Styles

These both give the same value:

nums[2]     // value at index 2
*(nums + 2) // same thing using pointer arithmetic

💡 Summary

  • Array name is a pointer to the first element
  • You can use pointers to loop through arrays
  • Pointer math makes it powerful (but be careful!)

Arrays and pointers are memory-level buddies. Learn one, understand both! 💡