C++ Pointers and Arrays

The array name itself acts as a pointer to the first element of that array.

In the c++ programming language, when we declare an array, the compiler allocates the required amount of memory and also creates a constant pointer with the array name and stores the base address of that pointer in it. The address of the first element of an array is called a base address of that array.

That means the array name itself acts as a pointer to the first element of that array.

  • An array name is a constant pointer.
  • We can use the array name to access the address and value of all the elements of that array.
  • Since array name is a constant pointer we can't modify its value.
Example code
#include <iostream>

using namespace std;

int main()
{
    string colors[5] = {"Red", "Green", "Blue", "Yellow", "Orange"};

    cout << "Base address is " << &colors[0] << endl;

    cout << "Base address is " << colors << endl;   // array name as pointer

    cout << "colors[3] = " << *(colors+3) << endl;   // Accessing value using pointer array

    colors++;    // Generates an error

    return 0;
}
Output
program to illustrate pointer and array

In the above example, the array name colors can be used as follows.

Addresses

  • colors equal to &colors[0]
  • colors + 1 equal to &colors[1]
  • colors + 2 equal to &colors[2]
  • colors + 3 equal to &colors[3]
  • colors + 4 equal to &colors[4]

Values

  • *colors equal to colors[0]
  • *(colors + 1) equal to colors[1]
  • *(colors + 2) equal to colors[2]
  • *(colors + 3) equal to colors[3]
  • *(colors + 4) equal to colors[4]