News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

Dynamic array

Started by roze, July 06, 2010, 06:54:24 AM

Previous topic - Next topic

roze

hi.I read a code which define dynamic array like code below but I want know why to mov es in PNTR+2 ? and also can i only save es:[di] and use it?

mov cx, 1024
malloc
jc MallocError
mov word ptr PNTR, DI
mov word ptr PNTR+2, ES

MichaelW

I'm not sure what malloc you are using, so I used a DOS function to allocate the memory.

.model small
.stack
.data
    fpMem dd 0
.code
.startup

    ;------------------------------------------------------------
    ; Allocate memory for a 256-WORD array. The function expects
    ; the size to be specified in 16-byte paragraphs, not bytes.   
    ;------------------------------------------------------------

    mov ah, 48h
    mov bx, (256*2)/16
    int 21h

    jnc @F

    ;------------------------------------
    ; Error handling code would go here.
    ;------------------------------------

  @@:
    ;----------------------------------------------------------------
    ; Assuming no error, the function returns the segment address of
    ; the allocated block in AX. Since the array is in a different
    ; segment from our data segment, to access it we need to use a
    ; FAR pointer. For a FAR pointer the 16-bit offset address is
    ; stored in the low-order WORD and the 16-bit segment address in
    ; the high-order WORD. Since the function returns only the segment
    ; address, we leave the pointer offset address set to zero and
    ; store only the segment address. Note that we must specify WORD
    ; PTR for the destination operand as otherwise the assembler will
    ; assume it is the defined size (a DWORD), and since the source
    ; operand is a WORD it will return error A2022:
    ; instruction operands must be the same size.
    ;----------------------------------------------------------------

    mov WORD PTR fpMem+2, ax

    ; . . .

    ;------------------------------------------------
    ; To access the array, start by loading the FAR
    ; pointer into ES:DI.
    ;------------------------------------------------

    les di, fpMem

    ;------------------------
    ; Get the first element.
    ;------------------------

    mov ax, es:[di]

    ;----------------------------------
    ; And copy it to the last element.
    ;----------------------------------

    mov es:[di+255*2], ax

.exit
end

eschew obfuscation