开发者

2 Dimentional array dereferencing ,how to evaluate through pointers

a[2][3] = {{-3,14,5},{1,-10,8}}

*(a[j]+k) 
*(a[j+k-2]) 
(*(a+j))[k]) 

(*(a+k-1))[j] 
*((*(a+j))+k)) 

(**(a+j)+k) 
*(&a[0][0]+j+k) 

when i printf th开发者_Go百科ese i get Output: 8 1 8 -10 8 3 1 respectively Please if anyone can explain in detail how the values are coming ,i am a new starter please pardon me for bad formatting here and also bothering you for with so much work :)


I assume j == 1 and k == 2:

*(a[j]+k) == *(a[1]+2) :

    a[1] = {1, -10, 8};
    So a[1]+2 is a pointer to 8, and *(a[1]+2) == 8

 

*(a[j+k-2]) == *(a[1+2-2]) == *(a[1]):

    a[1] = {1, -10, 8}
    Since *a[1] is the value of the first element in a[1], the expression evaluates to 1

 

(*(a+j))[k] == (*(a+1))[2]:

    a+1 is a pointer to the second element in a, so *(a+1) == a[1] = {1, -10, 8}
    a[1][2] == 8

 

(*(a+k-1))[j]  == (*(a+2-1))[1] == (*(a+1))[1]:

    *(a+1) == a[1] (see the last answer)
    a[1][1] == -10

 

*((*(a+j))+k) == *((*(a+1))+2):

     *(a+1) == a[1], so the expressions is equivalent to *(a[1]+2)
     *(a[1]+2) is equivalent to a[1][2] for the same reasoning as above, which is 8

 

(**(a+j)+k)  == (**(a+1)+2):

    *(a+1) = a[1]
   **(a+1) = a[1][0] == 1
     Adding 2 to that gives 3

 

*(&a[0][0]+j+k) == *(&a[0][0]+1+2) == *(&a[0][0]+3):

    &a[0][0] == a[0]
    *(a[0]+3) == a[0][3];

This last one is returning 1, because it is extending in memory past the end of a[0] into a[1], and you're getting a[1][0]. I think this behavior is actually undefined though. It depends on whether the C standard guarantees that an initialized 2D array will be allocated sequentially in memory or not, and could result in a Segmentation fault or worse.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜