tags:

views:

138

answers:

2
char *a[]={"diamonds","clubs","spades","hearts"};
char **p[]={a+3,a+2,a+1,a};
char ***ptr=p;
cout<<*ptr[2][2];

why does it display h and please explain how is the 2d array of ptr implementing and its elements

+12  A: 

Note that x[y] binds tighter than *x, so the expression *ptr[2][2] is interpreted as *(ptr[2][2]).

Also note that x[y] == *(x+y).

Therefore

*(ptr[2][2]) == *(p[2][2])    // ptr = p
             == *((a+1)[2])   // p[2] == a+1
             == *(*(a+1+2))   // x[y] == *(x+y)
             == *(*(a+3))     // 1+2 == 3
             == *(a[3])       // *(x+y) == x[y]
             == *("hearts")   // a[3] == "hearts"
             == "hearts"[0]   // *x == *(x+0) == x[0]
             == 'h'
KennyTM
I sure wish we could see who just made that edit. I assume that only moderators can make edits without a trace like that. The edit is fine with me, but the anonymity seems uncool...
sblom
@sblom: No, it's just I removed that within 5 minutes.
KennyTM
Ahh, I see. Cool.
sblom
This helped me to understand these types of declarations a little better: http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html.
helixed
+4  A: 

See KennyTM's excellent answer for an explanation... but I thought this would be the perfect case for professing the use of your debugger to "visualize" memory.. and provide an easy answer to this type of question.

alt text

JRL