C++ Pointers and Arrays

Relationship between Array and Pointers

  • The name of the array is a const pointer to the beginning of the array. It contains the address of first array element.

    int score[100];
    the score is equal to &score[0].
  • A pointer that points to the beginning of array can access any element of array using pointer arithmetic.

    int score[100];
    int *ptr = score;
    

    Now we can access fourth element of array as *(ptr + 3) or ptr[3]. Internally, any array element access using index is implemented using pointer.

  • A pointers variable can also store address of individual array elements like address of single variables.

    int score[100];
    int *ptr = &score[4];
    
  • On incrementing a pointer who is pointing to an array element, it will start pointing to next array element.

    int score[100];
    int *ptr = score;
    

    Currently, ptr is pointing to first element of array but when we increment it

    ptr = ptr + 1;
    

    It will start pointing to 1st element of array. Incrementing a pointer increases its value by the number of bytes of its data type.

    1. On incrementing, a pointer pointing to an integer(4 bytes) array jumps 4 bytes.
    2. On incrementing, a pointer pointing to a character(1 bytes) array jumps 1 bytes.

C++ Program to print array elements using array index and pointers

#include <iostream>
using namespace std;
 
int main () {
   int score[6] = {1, 2, 3, 4, 5, 6};
   int i, *ptr;
 
   // printing array elements using array index
   for(i = 0; i < 6; i++){
       cout << score[i] << " ";
   }
   cout << endl;
   
   // Initializing pointer
   ptr = score;
   // printing array elements using pointer
   for(i = 0; i < 6; i++){
       cout << *(ptr) << " ";
       // Incrementing pointer
       ptr++;
   }
   
   return 0;
}

Output
1 2 3 4 5 6
1 2 3 4 5 6

In above program, we first initialize a pointer with base address of an integer array. On incrementing this pointer inside for loop, it keeps on pointing to next array element.

  • Pointers and Arrays are interchangeable in many cases but their one difference. Name of an array is a constant pointer, which always points to first element of array. We can use array name in pointer arithmetics as long as we are not changing it's value.
    int score[100];
  • (score + 1) is a valid expression because here we are not changing value of score whereas *(score++) is invalid.