arrays and pointers

#include<stdio.h>
int main()
{
static int a[2][2]={1,2,3,4};
int i;int j;
static int *p[]={(int*)a,(int*)a+1,(int*)a+2};
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d,%d,%d,%d\n",*(*(p+i)+j),*(*(j+p)+i),*(*(i+p)+j),
                               *(*(p+j)+i));
}
}
return 0;}
can anyone explain the code plz??

Comments

  • line 6 is wrong -- there is no such element as a+2
  • no it executes
    the output is
    1,1,1,1
    2,2,2,2
    2,2,2,2
    3,3,3,3
  • "No" -- what?? It executes on your computer only by pure luck, not because it's right.

    The entire program exhibits undefined behavior because arrays-of-arrays are not guaranteed to be in contiguous memory locations. For a complete discussion of that read this article
  • trust me! it executes !
  • Well, if you seem to know more than I do then you explain the program to us.
  • I believe you when you say it runs. That's the nature of programs with undefined behavior - they may run perfectly is one possible output, especially with arrays that are very trivial in size. They're very likely to be in contiguous memory locations, even though they don't HAVE to be, by the C standard.

    More than that however, this program is one whose algorithm is opaque to those not experienced with it. Imagine for a moment that you needed to add a feature or fix a bug in it. The Yuck! factor sweeps in like a tsunami.

    So imo, it has two strikes against it - 1) It's not compliant with the C standard, and 2) it's unnecessarily complex, and yes, clear simple code certainly is a goal for our code. Not as important as accuracy, but still important. Code worth keeping around, is code that someday will probably have to be modified by someone other than the original author.
Sign In or Register to comment.