Как мне изменить значение последнего индекса в массиве? - PullRequest
1 голос
/ 31 января 2020

Я объявил массив из 8 элементов, каждый размером два байта.

ar dw 8 dup(6)

Как изменить значение последнего индекса этого массива (ar)?

Ответы [ 2 ]

1 голос
/ 31 января 2020

Вот шаблон программы TASM для вас:

.MODEL small
.486
.STACK 1000h

.DATA
    ar      DW 8 DUP (6)
    decstr  DB 8 ('$')

.CODE
main PROC
    mov ax, @DATA                       ; Initialize DS - Don't forget it!
    mov ds, ax

; You might count the array from 1 to 8, but the computer counts from 0 to 7.
; So, decrement the wished index by 1: (LENGTH arr - 1)
; Since a WORD consumes 2 bytes, the index has to be multiplied by this size,
; so that the computer can point into the array at the right address.
; The size of a WORD (2 bytes) can be determined by the directive TYPE
LASTINDEX =  (LENGTH ar - 1) * TYPE ar

    mov [ar + LASTINDEX],  7

; Print the decimal numbers of the array to the console
    lea si, [ar]                        ; SI gets the address of ar
    mov cx, 8                           ; Counter - do the loop eight times
    L1:
    mov ax, [si]                        ; AX gets the value of the element
    lea di, [decstr]                    ; DI gets the address of decstr
    call ax2dec
    mov WORD PTR [di], '$ '             ; Insert a space into the string
    mov ah, 09h                         ; DOS function: print string
    lea dx, [decstr]                    ; DX gets the address of decstr
    int 21h                             ; Call DOS
    add si, 2                           ; Set the pointer to the next element
    loop L1                             ; Do it CX times

    mov ax, 4C00h                       ; DOS function:Exit with Code 0
    int 21h                             ; Call DOS
main ENDP

ax2dec PROC STDCALL USES ax bx cx dx es ; Args: AX - number; DI - pointer to string
    push ds                             ; Initialize ES for STOSB
    pop es
    mov bx, 10                          ; Base 10 -> divisor
    xor cx, cx                          ; CX=0 (number of digits)

  Loop_1:
    xor dx, dx                          ; Clear DX for division
    div bx                              ; AX = DX:AX / BX   Remainder DX
    push dx                             ; Push remainder for LIFO in Loop_2
    inc cx                              ; inc cl = 2 bytes, inc cx = 1 byte
    test ax, ax                         ; AX = 0?
    jnz Loop_1                          ; No: once more

  Loop_2:
    pop ax                              ; Get back pushed digits
    or al, 00110000b                    ; Conversion to ASCII
    stosb                               ; Store only AL to [ES:DI] (DI is a pointer to a string)
    loop Loop_2                         ; Until there are no digits left
    mov byte ptr es:[di], '$'           ; Termination character for 'int 21h fn 09h'
    ret
ax2dec ENDP                             ; Ret: DI - pointer to terminating '$'

END main                                ; Directive to stop the compiler.

Если примеры вашего учителя отличаются, спросите их, почему! TASM древний, но его учителя еще более древние; -)

0 голосов
/ 31 января 2020

@ комментариев fuz было достаточно, чтобы ответить на ваш вопрос.

mov word [ar+2*7], 7

===

Индекс вашего первого элемента: [ar].

Ваш массив имеет 8 элементов размером по два байта (слово).

Таким образом, последний индекс будет [ar + 2 * (8-1)]. ([ar + 16] не будет в границах массива, поскольку он будет ссылаться на следующие два байта).

===

На всякий случай, если вы думаете почему пренебрегают другими возможностями, вот краткое объяснение для вас.

Инструкция mov используется для передачи значения между двумя регистрами или регистром и ячейкой памяти. Передача из памяти в память невозможна из-за физических ограничений. Вы можете использовать временно использовать регистр для достижения этой цели, хотя. (3 ins)

Примечание: Transfer означает копирование.

Теперь по умолчанию mov передает байт в ячейку памяти, если это необработанное значение или это старший или младший байт регистра ,

Для краткости мы можем использовать слово, чтобы сказать ассемблеру, что данный адрес получит 2-байтовое значение, поэтому управляйте передачей соответствующим образом.

===

...