Facebook Page Twitter Page LinkedIn Page
× C++ Q&A


The concept of arrays is strongly related to pointers. A pointer that points to the beginning of an array can access the array by using either pointer arithmetic or array-style indexing. Pointers and arrays support the same set of operations, with the same meaning for both. The main difference being that pointers can be assigned new addresses, while arrays will always represent the same address blocks.

Example:

In the below example, an array called MyArray and a pointer called p are created. pointer p is assigned the address of MyArray. The pointer arithmetic and array-style indexing is used to assign all elements of MyArray.

#include <iostream>
using namespace std;
 
int main (){
    int MyArray[5];
    int *p;
    p = MyArray;
    *p = 100;
    p++; *p=200;
    p = &MyArray[2]; *p = 300;
    p = MyArray + 3;  *p = 400;
    p = MyArray;  *(p+4) = 500;
    for (int i = 0; i <= 4; i++){
        cout<<MyArray[i]<<"\n"; 
    }
    return 0;
}

The output of the above code will be:

100
200
300
400
500