-4
 main()
  {
     int a[2][3][2]={{{1,2},{9,8},{3,7}},{{2,2},{1,4},{5,4}}};
     printf("%d %d %d",a[1]-a[0],a[1][0]-a[0][0],a[1][0][0]-a[0][0][0]);
  }

// Output for this code is coming as 3 6 1

I need to know how this output comes. I have searched many websites for the same , but didn't got any appropriate answer.

1 Answers1

2
 int a[2][3][2]={{{1,2},{9,8},{3,7}},{{2,2},{1,4},{5,4}}};
 printf("%d %d %d",a[1]-a[0],a[1][0]-a[0][0],a[1][0][0]-a[0][0][0]);

Dividing:

 printf("%d",a[1]-a[0]); // result = 3 (because a[x] decays into int (*)[2])

 {{{1,2},{9,8},{3,7}},{{2,2},{1,4},{5,4}}}
   _____ _____ _____
     1     2     3    (elements of type int[2])

 printf("%d",a[1][0]-a[0][0]); // result = 6 (because a[x][x] decays into int *)

 {{{1,2},{9,8},{3,7}},{{2,2},{1,4},{5,4}}}
    _ _   _ _   _ _
    1 2   3 4   5 6   (elements of type int)

 printf("%d",a[1][0][0]-a[0][0][0]); // result = 1 (because 2 - 1 = 1)

 {{{1,2},{9,8},{3,7}},{{2,2},{1,4},{5,4}}}
    ^ a[0][0][0]        ^ a[1][0][0]

And note that the correct format for printf is:

printf("%ld %ld %d",a[1]-a[0],a[1][0]-a[0][0],a[1][0][0]-a[0][0][0]); /* C89 */

or

printf("%td %td %d",a[1]-a[0],a[1][0]-a[0][0],a[1][0][0]-a[0][0][0]); /* C99 */
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • 1
    +1: nice answer, but note that %zu is not strictly correct for a ptrdiff_t: http://stackoverflow.com/questions/7954439/c-which-character-should-be-used-for-ptrdiff-t-in-printf – Paul R Oct 25 '14 at 17:45