Site icon i2tutorials

Pointers and Arrays

Pointers and Arrays

 

A pointer provides efficient access to elements within an array.

The following facts refer to the relationship between pointers and arrays.

 

Example 1 using Unary Operator(++):

 

#include<stdio.h>
main()
{
int a[5]={10,20,30,40,50};
int i,*p;
p=&a[0]; // OR p=a;
for(i=0;i<5;i++)
{
printf("Address p=%u value *p=%d\n",p,*p);
p++;
}
}

 

Output:

 

 

In the above program, an integer array of size 5 is declared and initialized. Then, the address of the 0th element of the array is assigned to the integer pointer „p‟. Within the loop, the address of the array element is stored in „p‟, and the contents of the memory location pointed to by „p‟ are printed. When „p‟ is incremented, the value stored in „p‟ is incremented by 2 to point to the next element of the array( as each integer occupies 2 bytes of memory).

Note: p++ increments the memory address similarly p- – decrements the memory address which is stored in the pointer variable.

 

Example 2 using Unary Operator(- -):

 

#include<stdio.h>
main()
{
float f[5]={10.5,12.3,20.6,25.8,28.7};
int i;
float *pf=&f[4];
for(i=0;i<5;i++)
{
printf("Address f=%u value *pf=%f \n",f,*pf);
pf--;
}
}

 

Output:

 

 

In the above example program, the pointer occupies the float address memory which occupies 4 bytes of memory space. So, for each increment, the pointer increments four bytes of memory which is specified in the output.

 

Exit mobile version