POINTERS AND ARRAYS - C-Tutorial

Latest

Monday, 3 October 2016

POINTERS AND ARRAYS

POINTERS AND ARRAYS


Case 1: generating pointer to array (or) passing pointer to array
  • ·        whenever a single dimensional array is declared the C-compiler automatically creates a pointer variable and it stores the base address of the array.
  • ·        Now the pointer can refer every element in single dimensional array


                        i.e., &x[i] = x+i                       x[i] = *(x+i)

            #include<stdio.h>
#include<conio.h>
main()
{
int i,a[5],n;
clrscr();
printf("\n Enter n value: ");
scanf("%d",&n);
printf("\n Enter the %d array elements: ",n);
for(i=0;i<n;i++)
scanf("%d",(a+i));
printf("\n The given array elements are: ");
for(i=0;i<n;i++)
printf(" %d",*(a+i));
getch();
}

Case 2: passing pointer to two dimensional array:
  • ·        whenever a two dimensional array is declared the C-compiler automatically creates a pointer array with the same name of two dimensional array and it stores the base address of the each row.
  • ·        whenever a pointer array is created the C-compiler automatically creates a pointer pointer variable with the same name of the pointer array name and it stores the address of the pointer array.
  • ·        Now the pointer can refer every element of two dimensional array


            Similarly, for double dimensional arrays,

            &x[i][j] = (*(x+i)+j)                x[i][j] = *(*(x+i)+j)

            Example program:
#include<stdio.h>
#include<conio.h>
main()
{
int a[3][3],i,j,m,n;
clrscr();
printf("\n Enter m,n values: ");
scanf("%d%d",&m,&n);
printf("\n enter %d*%d elements",m*n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d", (*(a+i)+j));
printf("\n The array elements are: ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d", *(*(a+i)+j));
getch();
}


No comments:

Post a Comment