How do I access double pointer from C code in ASM&

2020-08-09 05:46发布

问题:

I have a main.c function which has the following statement:

int  initarr(int**arr, int n, int (*initfunc)(int));

Then I call the function in c like that:

success = initarr(&arr, n, getNum); 

The question is, in assembly code, in MODEL SMALL, the first argument in the function above will be in the memory as WORD or DWORD?

In other words, when I write the code, will this work:

PUSH BP
MOV BP,SP

PUSH DI
MOV DI, WORD PTR[BP+4] ; DI will hold &arr.

And now DI will hold arr's address.

If it is true, How will I be able to access arr[0]'s value if so?

PUSH BP
MOV BP,SP

PUSH DI
PUSH BX
MOV DI, WORD PTR[BP+4]
MOV BX, WORD PTR[DI]

Will BX hold the address of the array? I mean, the address of the first cell?

If so, how can I access arr[0] now?

Perhaps MOV DX, WORD PTR[BX] ?

回答1:

In model small, addresses are sized 2 bytes. A double pointer is still an address!

in order to access arr[0], you would write the following:

MOV DI, [BP+4]  ; no need casting, DI register is sized 2 bytes.
MOV SI, [DI]    ; get what DI is pointing to, and put it to SI. 
                ; you could say: DI=arr[][], SI = arr[]
MOV AX, [SI]    ; now AX = arr[0]

if we would like to access arr[i], we would do the following:

MOV DI, [BP+4]  
MOV SI, [DI]     
MOV AX, i
SHL AX, 1   ; because arr[] contains int numbers which are sized 2 bytes.
ADD SI, AX
MOV AX, [SI]    ; now AX = arr[i].  SI = &arr[i].