Thursday, December 29, 2011

Accident of syntax !!

Once,I read in a book-"A C programmer without knowledge of pointers is like a fish which doesn't know how to swim".After this post,actually, you will be able to appreciate this.Basically,i'll be dicussing a very simple operation in C, i.e scanning & printng an array,rather a 2-D array.I'll discuss about 3-4 ways in which we can use pointers to print a 2-D array,coz today,if you know only: printf("%d ",a[i][j]);  to print a 2D-array,u need to improve man!.

So,starting with scanning a 2-D array(i'll be talking of an array consisting of int elements):
scanf("%d",&a[i][j]);
now,I don't know that why to use this '&' operator in scanning,while we know that the name of the array stores the beginning address of that array, and we can access all the elements of that array manupulating the name.What about this:
int a[3][2];
 for(int i=0;i<3;i++)
 {
  for(int j=0;j<2;j++)
   scanf("%d",*(a+i)+j);
 }
as we all know, a 2-D array consists of a series of 1-D arrays.Here, *(a+i) takes the pointer to the successive 1-D ararys and *(a+i)+j is incremented accordingly to scan successive integers. 
here,a-'name of the array',acts like a special pointer,which on incrementing 'i' by 1,points to the next 1-D array.
Basically,*(a+i) is equivalent to a[i],i.e ith element of that 2-D array,which actually refers to ith 1-D array, so a[i] gives the base address of ith 1-D array and '+j' refers to the address of  the jth element after the first element.
Now comes the printing:
Using above method,we know how to point to address of each element of a 2-D array,so we can also print their values using 1 more "accident of syntax"!, i.e. '*' operator (It was described by Ritchie himself as such).
 for(int i=0;i<3;i++)
 {
         for(int j=0;j<2;j++)
              printf("%d",*(*(a+i)+j));
 }

There is an another method:
for(int i=0;i<2;i++)
{
         for(int j=0;j<3;j++)
             printf("%d ",*(((int *)a)+i*3+j));
}
I think this 'i*3+j' is clear.Main point to notice here is that I m typecasting 'a' to an int pointer.I need to do this because as I mentioned earlier,on incrementing a, it points to the next 1-D array, but here,we want it to increase int by int.
This is my favourite method.

The next method is kind of a extension of this method:
for(int i=0;i<2;i++) 
{
         int *p=a+i;
         for(int j=0;j<3;j++)
               printf("%d",*(p+j));
}
here,instead of typecasting 'a' into an int pointer,I m originally taking an int pointer, and in every iteration,I m copying the base address of the corresponding 1-D array in that int pointer and then incrementing it to successive integers in that 1-D array.
In C,u need to have a good control over changing data-types of pointers.

So,these were few techniques to make your programme more interesting.
Hope,this is helpful..:)


hostgator coupon 2012

No comments: