I v porblem in assembly 8086, I can't use 2D array when I m using like this mov ar[cx][dx] then arising error and when I want to us SI and DI both in arrary then also find error. I need answer quickly thanks for your help
I would be very impressed in a CPU that provided array lookup semantics in its assembly language. Or rather, I would be annoyed if it meant something more important had been sacrificed.
The general way to do array lookup in assembly is by doing the calculation yourself to turn the two indexes for a 2D array into a single index for a 1D array, and adjust for the element size. For example (pseudo-code):
ax = cx * major_dimension
ax = ax + dx
ax = ax * element_size
ax = peek[base+ax]
where major_dimension
is one of the dimensions of the 2D array (which dimension you use depends entirely on how the data is laid out in memory), element_size
is the size of each element, base
is the start of the array and cx/dx are the indexes you're using to access the array.
For example, if you have a 3-by-4 (a[0-2][0-3]
) array at memory location 0x0700
and these are 32-bit integers:
+--------+--------+--------+--------+
0x0700: | a[0,0] | a[0,1] | a[0,2] | a[0,3] |
+--------+--------+--------+--------+
0x0710: | a[1,0] | a[1,1] | a[1,2] | a[1,3] |
+--------+--------+--------+--------+
0x0720: | a[2,0] | a[2,1] | a[2,2] | a[2,3] |
+--------+--------+--------+--------+
To find array element a[n,m]
, you calculate the major index multiplied by four plus the minor index, scale it to the correct element size (4 bytes) then add the base. To find element a[2,1]
addr = base + (n * 4 + m) * 4
= 0x0700 + (2 * 4 + 1) * 4
= 0x0700 + (8 + 1) * 4
= 0x0700 + (9 ) * 4
= 0x0700 + 36
= 0x0700 + 0x24
= 0x0724
Then that's the address you use for looking up the 1D array.
And, based on the comment that:
ar db 3dup(3dup(0))
mov ar[bx][si],al
would work, that's not quite right (ar[bx][si]
is masm-specific syntax equivalent to ar[bx+si]
).
All that does is a simple addition of the ar
address with the bx
and si
registers. It does not scale the bx
or si
register to take into account the major dimension and it does not scale the bx+si
value for the element size. So it will only work as-is for a 2D array of bytes where the major dimension is 1, which I'm pretty sure would make it a 1D array :-)
To work for any case, you would first need to multiply bx
or si
(depending on which is being used for the major dimension) by the major dimension then both bx
and si
by the element size.
I'm not really clear on the exact question you're asking but are you after something like this (using base/indexed addressing mode)?
lea bx, array_base
mov si, array_index
mov ax, [bx][si]