Easy Tutorial
❮ Cpp Return Arrays From Function Cpp Inheritance ❯

C++ Pointers vs Arrays

C++ Pointers

Pointers and arrays are closely related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer to the beginning of an array can access the array by using pointer arithmetic or array indexing. Consider the following program:

Example

#include <iostream>

using namespace std;
const int MAX = 3;

int main ()
{
   int  var[MAX] = {10, 100, 200};
   int  *ptr;

   // Array address in pointer
   ptr = var;
   for (int i = 0; i < MAX; i++)
   {
      cout << "Address of var[" << i << "] is ";
      cout << ptr << endl;

      cout << "Value of var[" << i << "] is ";
      cout << *ptr << endl;

      // Move to the next position
      ptr++;
   }
   return 0;
}

When the above code is compiled and executed, it produces the following result:

Address of var[0] is 0x7fff59707adc
Value of var[0] is 10
Address of var[1] is 0x7fff59707ae0
Value of var[1] is 100
Address of var[2] is 0x7fff59707ae4
Value of var[2] is 200

However, pointers and arrays are not completely interchangeable. For example, consider the following program:

Example

#include <iostream>

using namespace std;
const int MAX = 3;

int main ()
{
   int  var[MAX] = {10, 100, 200};

   for (int i = 0; i < MAX; i++)
   {
      *var = i;    // This is correct syntax
      var++;       // This is incorrect
   }
   return 0;
}

Applying the dereference operator * to var is perfectly legal, but modifying the value of var is illegal. This is because var is a constant pointer to the beginning of the array and cannot be used as an lvalue.

Since an array name corresponds to a constant pointer, you can still use pointer-like expressions as long as the array's value is not changed. For example, the following statement assigns 500 to var[2]:

*(var + 2) = 500;

The above statement is valid and compiles successfully because var is not changed.

C++ Pointers

❮ Cpp Return Arrays From Function Cpp Inheritance ❯