+2 votes
in Class 12 by kratos

What is the relationship between array and pointers? Give an example.

1 Answer

+2 votes
by kratos
 
Best answer

There is a relationship between arrays and pointers. This is explained with the following example;
void main()
{
int a[5], i;
cout<< “Enter the 5 elements”;
for (i=0; i<5; i++)
cin >> (a+i);
cout<< “The entered array elements are ” << endl;
for (i=0; i<5; i++)
cout>>
(a+i);
}

In the above program, ‘a’ is a integer array with five elements, and ‘i’ is integer variable. During the compilation, only the first element address of the array is stored i. e., a[0]. To access every other element of the array, it calculates the address by adding ‘i’ units to the base address i.e., a[0]. The number of bytes in each unit of ‘i’ is 2 bytes.

The line cin >> *(a+i); can be interpreted as follows;
Consider the base address of a is 1000, then
Base address of a + 0 = 1000 + 0 = 1000 where i = 0 unit of 2 bytes
Base address of a + 1 = 1000 + 2 = 1002 where i = 1 unit of 2 bytes
Base address of a + 2 = 1000 + 4 = 1004 where i = 2 units of 2 bytes
Base address of a + 3 = 1000 + 6 = 1006 where i = 3 units of 2 bytes
Base address of a + 4 = 1000 + 8 = 1008 where i = 4 units of 2 bytes.

...