Monday 15 July 2013

Explanation for the output of 3d array code in C -



Explanation for the output of 3d array code in C -

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 code coming 3 6 1

i need know how output comes. have searched many websites same , didn't got appropriate answer.

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 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 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 right format 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 */

c

No comments:

Post a Comment