Multi-dimensional array: Difference between revisions

no edit summary
No edit summary
No edit summary
Line 2,500:
121 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
</pre>
 
=={{header|X86-64 Assembly}}==
I was originally going to omit this, because multi-dimentional arrays simply don't exist in Assembly. But I decided to at least show how to use them.
<lang asm>
option casemap:none
 
printf proto :qword, :vararg
exit proto :dword
 
ROW_LEN equ (4*2) ;Length of the row, 2 rows of int so, 2 dwords
MEM_SIZE equ 4 ;1 dword, int
 
.data
;; A 2d array - 2 rows, 4 columns
;; int twodimen[2][4] = { {0,1,2,3},
;; {4,5,6,7}};
twodimen db 48 dup (0)
tpl db "%d",13,10,0
 
.code
main proc
local cols:qword
invoke printf, CSTR("--> Printing 2d..",10)
lea rbx, twodimen
mov cols, 0
;; Forgive me for the multiple loops, I'm just to lazy to
;; do the conditional jumps required for 2 for loops. -.-
@1:
mov rcx, cols
mov dword ptr [rbx+0*ROW_LEN + rcx*MEM_SIZE], ecx ;; first row, rcx column
inc cols
cmp cols, 3
jle @1
 
mov cols, 0
mov rdx, 4
@2:
mov rcx, cols
mov dword ptr [rbx+1*ROW_LEN + rcx*MEM_SIZE], edx ;; second row, rcx column
inc cols
inc edx
cmp cols, 3
jle @2
invoke printf, CSTR("--> Printing columns in row 1",10)
mov cols, 0
@3:
mov rcx, cols
mov esi, dword ptr [rbx+0*ROW_LEN + rcx*MEM_SIZE]
lea rdi, tpl
call printf
inc cols
cmp cols, 3
jle @3
 
invoke printf, CSTR("--> Printing columns in row 2",10)
mov cols, 0
@4:
mov rcx, cols
mov esi, dword ptr [rbx+1*ROW_LEN + rcx*MEM_SIZE]
lea rdi, tpl
call printf
inc cols
cmp cols, 3
jle @4
 
 
mov rax, 0
xor edi, edi
call exit
leave
ret
main endp
</lang>
{{out}}
<pre>
--> Printing 2d..
--> Printing columns in row 1
0
1
4
5
--> Printing columns in row 2
4
5
6
7
</pre>
So as stated previously. Multi-dimentional arrays DO NOT exist in Assembly. However one way to reference them is as displayed above.. It's syntax is ..
<pre>
row * row length + column * member size
</pre>
However, a C compiler for example doesn't use such a method. Infact, a compiler will generally output something like..
<lang asm>
mov dword ptr [rbp-48], 0
mov dword ptr [rbp-44], 1
.....
mov ecx, dword ptr [rbp-48]
</lang>
If you're curious you can use gcc's -S command line option to print out AT&T syntax'd ASM from C/C++ files or something like Cutter if you're more into the Intel syntax.