Software & Finance





Turbo C - Pointer to an Array





Here is a simple example on how to declare and use pointer variables that is used to point to an array in C Programming Language.

 

Pointers are used to point to a memory location. In Turbo C, size of pointer variable in 2 bytes since it is a 16 bit applications where as in visual c++ it would be 4 bytes since it 32 bit applilcation. Today 64 bit compilers will allocate 8 bytes for a pointer variable.

 

The following is a good example illustrating the concept of pointer that is pointing to an array. p is an pointer that points to integer array called myarray. Initially when p is assigned, it is pointing to the first location of the array. When it is incremented in the loop, it is pointing to next element in the array.

 


Source Code


#include <stdio.h>

 

void main()

{

   int i;

   int myarray[] =  { 100, 200, 300, 400, 500 };

   int *p = myarray;

   int numelements = sizeof(myarray) / sizeof(myarray[0]);

  

   for(i = 0; i < numelements; i++)

   {

      printf("Element[%d] = %d\n", i + 1, *p);

      p++;

   }

}

Output


Element[1] = 100

Element[2] = 200

Element[3] = 300

Element[4] = 400

Element[5] = 500