代码之家  ›  专栏  ›  技术社区  ›  lefrost

为什么在从字符串中获取和显示字符时会得到意外的结果?

  •  0
  • lefrost  · 技术社区  · 6 年前

    我正在尝试获取字符串的第二个字符(例如 e Test ). 用emu8086编译。

    str db 'Test$'
    ...
    mov si, 1       ; get second character of str
    mov bl, str[si] ; store the second character
    
    mov ah, 2       ; display the stored character
    mov dl, bl
    int 21h
    

    输出为 e .

    str db 25
        db ?
        db 25 dup (?)
    ...
    mov ah, 0ah         ; accept a string
    lea dx, str         ; store input in variable str
    int 21h
    
    mov si, 1           ; get second character of str (??)
    mov bl, str[si]     ; store the second character
    
    mov ah, 2           ; display the stored character
    mov dl, bl
    int 21h
    

    我明白了 ♦

    当我将第二个代码段的“get second character of str”部分更改为:

    mov si, 3               ; get second character of str (why is it '3' instead of '1'?)
    mov bl, str[si]         ; store the second character
    

    我明白了

    我不明白。虽然它在第一个代码段中起作用,但为什么在第二个代码段中,我设置了 SI 3 而不是 1 ,如果我试图引用字符串的第二个字符?还是我使用的方法被误导了?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Ped7g    6 年前

    str[si] 不是某种类型/数组访问,但它将转换为指令内存操作数 [si+1234] str 指向内存中的。

    在你的第二个例子中 标签指向值为25(缓冲区的最大长度)的字节,然后 str+1 指向返回的输入长度字节(这是 ♦ 如果您试图将其打印为字符,则在输出时获得的值),以及 str+2 指向用户输入的第一个字符。所以要得到第二个字符你必须使用 str+3

    内存可通过字节寻址,因此您必须知道所有元素的字节大小,或者使用更多标签,如:

    str_int_0a:            ; label to the beginning of structure for "0a" DOS service
         db 25
         db ?
    str:                   ; label to the beginning of raw input buffer (first char)
         db 25 dup (?)
    

    然后在代码中,根据要执行的操作使用正确的标签:

    ...
    mov ah, 0ah         ; accept a string
    lea dx, str_int_0a  ; store input in memory at address str
    int 21h
    
    mov si, 1           ; index of second character of str
    mov bl, str[si]     ; load the second character
    
    mov ah, 2           ; display the stored character
    mov dl, bl
    int 21h
    ...
    

    推荐文章