Relationship Between Pointers and Array

0 ralfmaes7702577 November 13, 2020

In these tutorials, We will learn about the relationship between pointers and array. Before going through these tutorials, You must have knowledge about pointers.

The array of a pointer can be declared as 

data_type *pointer_name[size];

For Example

int *p[10];

This declares an array of 10 pointers, each of which points to an integer. The first pointer is called p[0], the second is p[1], and so on up to p[9]. Initially, these pointers are initialized and they can be used as below.

int a=10, b=100, c=1000;
p[0] = &a;
p[1] = &b;
p[2] = &c; and so on

Let’s take an example to make clear concepts on pointers and array.

#include <iostream>using namespace std;
int main() {
  int x[5] = {2, 4, 6, 8, 10};
  int* p;

  // p is assigned the address of the third element
  p = &x[2]; 
  cout << "*p = " << *p <<endl; //6  cout << "*(p+1) = " << *(p+1) << endl; //8  cout << "*(p-1) = " << *(p-1) << endl; //4

  return 0;
}

The output of the above program is:

*p = 6 
*(p+1) = 8 
*(p-1) = 4

In this example, We have assigned the address of the third element to pointer *p. So, when we print *p then 6 was displayed.

In the same way, *(p+1) displays fourth elements, and *(p-1) displays second elements.