Pointers and Arrays

Pointers and Arrays

The idea of array is incredibly a lot of related to the one with pointer. In fact, the identifier of an array is corresponding the address of its initial component, as a pointer is associated with the address of the primary component that it points to, so in fact they are identical thought. As an example, supposing these 2 declarations:

int num [20];
int * p1;
The following assignment operation would be valid:
p1 = num;

After that, p1 and num would be equivalent and would have identical properties. The only distinction is that we tend to could modification the value of pointer p1 by another one, whereas num can continuously purpose to the primary of the twenty elements of kind integer with that it had been outlined. Therefore, unlike p1, that is a normal pointer, num is an array, and an array are often thought-about a constant pointer. Therefore, the subsequent allocation wouldn’t be valid:

num = p1;

Because num is an array, thus it operates as a constant pointer, and that we cannot assign values to constants.
Due to the characteristics of variables, all expressions that embrace pointers within the following example are absolutely valid:

// arrays and pointers
#include
using namespace std;
int main ()
{
int num [5];
int * p1;
p1 = num; *p1 = 10;
p1++; *p1 = 20;
p1 = &num[2]; *p1 = 30;
p1 = num + 3; *p1 = 40;
p1 = num; *(p1+4) = 50;
for (int n=0; n<5; n++)
cout << num[n] << ", ";
return 0;
}

Output
10, 20, 30, 40, 50,

In the chapter related to arrays we tend to used brackets ([]) many times so as to specify the index of part of the array to that we tend to needed to refer. Well, these bracket sign operators [] are a dereference operator referred to as offset operator. They dereference the variable they follow even as * will, however they additionally add the number between brackets to the address being dereferenced. For example:

array1[5] = zero; // array1 [offset of 5] = 0
*(array1+5) = zero; // pointed by (array1+5) = 0

These 2 expressions square measure equivalent and valid with each of array1 if array1could be array1 pointer or if array1 is an array.
You can download pdf of Pointers and arrays