Can someone tell me the flow of references in the second printf statement in the given code?
#include <stdio.h>
char *c[]={"ENTNG", "NST","AMAZI","FIRBE"};
char** cp[]={c+3, c+2, c+1, c};
char ***cpp= cp;
int main() {
printf("%s",**开发者_运维知识库++cpp);
printf("%s ",*--*++cpp+3);
printf("%s",*cpp[-2]+3);
printf("%s",cpp[-1][-1]+1);
}
char *c[]= {
"ENTNG",
"NST",
"AMAZI",
"FIRBE"
};
*c[]
evaluates to a character, so c []
points to characters and c
is an array of pointer-to-character. The elements of c
have been initialized to point to
the character arrays
"ENTNG", "NST", "AMAZI" and "PIRBE"
.
char** cp[]={c+3, c+2, c+1, c};
**cp[]
evaluates to a character,*cp[]
is a pointer-to-character, and cp []
is a pointer-to-pointer-to-character. Thus cp
is an array of pointers to pointer-to-character. The elements of cp
have been initialized to point to the elements of c
.
char ***cpp= cp;
***cpp
evaluates to a character, **cpp
points to a character, *cpp
points to a pointer-to-character,and cpp
points to a pointer-to-pointer-to-character.
*(*(++cpp)); // Increment cpp and then follow the pointers
Op : "AMAZI"
(*(--(*(++cpp))))+3; // Increment cpp,follow the pointer to cp[2],
// decrement cp[2],follow the pointer to c[0],
// index 3 from the address in c[0].
Op : "NG "
(*(cpp[-2]))+3; // Indirectly reference - 2 from cpp yielding cp[0],
// follow the pointer to c[3];
// index 3 from the address in c[3].
Op : "BE"
(cpp[-1][-1])+1 // Indirectly reference -1 from cpp yielding cp [1],
// indirectly reference - 1 from
// cp[1] yielding c[1],index 1 from the address in c[1].
Op : "ST"
The output would be AMAZING BEST
Source : The C Puzzle Book
Well the output is "AMAZING BEST".
You can check the evaluation order using the operator precedence table for C.
cout << (**++cpp) ;
// **++cpp =:= **(cpp = cp+1) =:= *(c+2) =:= "AMAZI"
// side-effect: cpp -> cp+1
cout << (*--*++cpp+3) << " ";
// *--*++cpp+3 =:= *--*(cpp = cp+2)+3 =:= *--(cp+2)+3 =:= *(cp[2] = c)+3 =:= "NG"
// side-effect: cpp -> cp+2, cp => {c+3, c+2, c, c}
cout << (*cpp[-2]+3);
// *cpp[-2]+3 =:= **(cp+2-2)+3 =:= *(c+3)+3 =:= "BE", thus print "BE"
cout << (cpp[-1][-1]+1) << endl;
// cpp[-1][-1]+1 =:= *(*(cp+2-1)-1)+1 =:= *(c+2-1)+1 =:= "ST"
return 0;
精彩评论