Thorux
Thorux

Reputation: 225

How to get the value of an array element in x86 assembly when I have the address of the first index

I need to call an assembly procedure in a C program. In my C program I have the address of an array and in my assembly procedure I need to obtain the value of the second index of the array. If I had the array itself as a parameter, it would be easier for me. Could you please tell me how could I get the content of the second element of the array?

In my C program, I am calling this function:

getIndex(&array[0]);  

If the parameter was not an address, my soluton in the assembly procedure would be this:

PUSH BP
MOV BP,SP
push SI

MOV SI,[BP+4]
ADD CX,SI
ADD SI,2
MOV AX,SI ; AX got the value of the second index of the array

How should I solve my issue? Thanks for helping.

Upvotes: 2

Views: 13602

Answers (1)

Samuli Hynönen
Samuli Hynönen

Reputation: 680

Basically you need one more memory address de-reference (the brackets), but there are also some additional issues with your code.

Looking at your code I assume that the size of elements in the array is 2 bytes, you are using the cdecl calling convention, and have a 16-bit processor. Here are the issues:

  1. If you push SI to the stack, you should also pop it
  2. You are adding the value of SI to CX but never use the value in CX
  3. The procedure does not revert BP and SP of the caller, nor return to where the procedure was called from

Here's the code with the issues fixed:

push bp
mov bp,sp
push si
mov si,[bp+4] ; si = address of the first element in the array
mov ax,[si+2] ; ax = value of the second element in the array
pop si        ; revert si
mov sp,bp     ; revert the caller's stack pointer
pop bp        ; revert the caller's base pointer
ret           ; jump to the instruction after the call

Upvotes: 2

Related Questions