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
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
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'
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.