Google News
logo
Pointer and arrays In C Language
Pointer can be used with array for efficient programming. The name of an array itself indicates the stating address of an array or address of first element of an array.

That means array name is the pointer to starting address or first elements of the array. If A is an array then address of first element can be expressed as &A[0] or A. The Compiler defines array name as a constant pointer to the first element. 

Pointers and arrays are closely related, the array expressions can be taken as pointer expressions, for example x[i] can be written as *(x+i)

Example : &x [0]->&*(x+0)_x therefore x->&x[0];

Hence, the expression “array name” without any index gives the address of first element which is called base-address of array.

Assuming that the base address of arr is 1000 and each integer requires two byte, the five elements will be stored as follows
Pointers

Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0]. Therefore arr is containing the address of arr[0] i.e. 1000.

arr is equal to &arr[0] // by default

We can declare a pointer of type int to point to the array arr.

      int *p;
      p = arr;
          or
      p = &arr[0]; //both the statements are equivalent.

Now we can access every element of array arr using p++ to move from one element to another.

NOTE: You cannot decrement a pointer once incremented.

  Program: The following program is an example of pointer arrays.
#include<stdio.h>
 #include< conio.h>
void disp (int *, int);
main( )
 {
  int i, a[10],n; 
  printf (“ enter the size of an array:”);
  scanf (“%d”, &n);
  printf (“ enter the array elements:”);
  for (i=0; i<n; i++)
    scanf (“%d”, &a[i]);
 disp (a,n);
 printf(“ array elements after sorting ” );
 for(i=0;i<n;i++)
 printf (“%d”, a[i]); 
}

 void disp(int a[ ], int n)
 {
  int i,j, temp; 
  for (i=0; i<n; i++)
   for (j=0; j<n; j++) 
        {
          if (a[j] > a[i])
        {
                temp = a[ j ]; 
               a[ j ] = a[ i ];
              a[ i ] = temp; 
        }
     }
 }
Output :

Enter the size of an array: 5
Enter the array elements: 20 30 10 50 40
Array elements after sorting: 10 20 30 40 50