/    /  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.

  • Array elements are always stored in adjacent memory slots regardless of the size of the array.
  • The size of the data type referenced by the pointer variable depends on the data type pointed out by the pointer.For example, if the pointer variable points to an integer data type, then it accesses two bytes in memory assuming one integer takes two bytes.
  • A pointer when incremented, always directs to a location after skipping the number of bytes needed for the data type pointed to by it.For instance, if a pointer variable points to an integer data type at a certain address, say 1000, then by incrementing the pointer variable, it points to the location 1002, if an integer data type takes up two bytes of information.

 

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:

 

Pointers and Arrays

 

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:

 

Pointers and Arrays

 

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.