Consider the following code that has syntax similar to C: 求救?

2016-03-29 12:06 pm
Consider the following code that has syntax similar to C:
int a[4][5][6][7];
a[1][2][3][4]=3;
a[3][2][1][0]=4;
a[2][2][4][4]=5;
a[2][3][5][0]=6;
Given that anint has a size of 4 bytes. Assume that a[0][0][0][0] is at the address of 2000. Find the address of
(i) a[1][2][3][4] if row major is used;
(ii)a[3][2][1][0] if row major is used;
(iii)a[2][2][4][4] if column major is used;
(iv) a[2][3][5][0] if column major is used.

ans:
(i) 1*5*6*7+2*6*7+3*7+4
(ii) 3*5*6*7+2*6*7+1*7+0
(iii) 2+2*4+4*4*5+4*4*5*6
(iv) 2+3*4+5*4*5*+0*4*5*6

完全唔知點計同個原理 求救
更新1:

唔係wow 點解你計出黎同我個model ans 完全唔同既?......

回答 (1)

2016-03-29 2:27 pm
✔ 最佳答案
以下計算依照維基百科中的公式參數, 請先參考註解一.
Sol :
維度 d = 4
N1*N2*N3*N4 = 4*5*6*7

( i )
( n1 , n2 , n3 , n4 ) = ( 1 , 2 , 3 , 4 )

offset
= n4 + N4*( n3 + N3*( n2 + N2*n1 ) )
= 4 + 7*( 3 + 6*( 2 + 5*1 ) )
= 4 + 7*( 3 + 6*7 )
= 4 + 7*45
= 319

address
= base address + offset
= 2000 + 319
= 2319 ..... Ans

( ii )
( n1 , n2 , n3 , n4 ) = ( 3 , 2 , 1 , 0 )

offset
= n4 + N4*( n3 + N3*( n2 + N2*n1 ) )
= 0 + 7*( 1 + 6*( 2 + 5*3 ) )
= 7*( 1 + 6*17 )
= 7*103
= 721

address
= 2000 + 721
= 2721 ..... Ans

( iii )
( n1 , n2 , n3 , n4 ) = ( 2 , 2 , 4 , 4 )

offset
= n1 + N1*( n2 + N2*( n3 + N3*n4 ) )
= 2 + 4*( 2 + 5*( 4 + 6*4 ) )
= 2 + 4*( 2 + 5*28 )
= 2 + 4*142
= 570

address
= 2000 + 570
= 2570 ..... Ans

( iv )
( n1 , n2 , n3 , n4 ) = ( 2 , 3 , 5 , 0 )

offset
= n1 + N1*( n2 + N2*( n3 + N3*n4 ) )
= 2 + 4*( 3 + 5*( 5 + 6*0 ) )
= 2 + 4*( 3 + 5*5 )
= 2 + 4*28
= 114

address
= 2000 + 114
= 2114 ..... Ans

註解一
offset 的計算公式, 請參考維基百科:
https://en.wikipedia.org/wiki/Row-major_order

註解二
你提供的答案只是 offset , 需要再加上 base address = 2000 , 才是題目要求的位址.


收錄日期: 2021-04-18 14:39:31
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20160329040635AAByvDc

檢視 Wayback Machine 備份