Home > OS >  Incrementing a pointer by 1 in an array of words: loading a word from half way between two words?
Incrementing a pointer by 1 in an array of words: loading a word from half way between two words?

Time:10-04

Consider the code below. If incrementing SI by 2 gives me the 2nd element of the array, what exactly would incrementing SI by 1 give me?

.data  
var dw 1,2,3,4  
.code  
LEA SI,VAR  
MOV AX,[SI]  
INC SI  
MOV AX,[SI]

CodePudding user response:

Statement var dw 1,2,3,4 tells the assembler to statically define eight bytes in memory at the beginning of .data segment. Layout of the data bytes will be

|01|00|02|00|03|00|04|00|

and the first MOV AX,[SI] will load AL with 01 and AH with 00.
When you increment SI only by 1, the next MOV AX,[SI] will load AL with 00 and AH with 02.
If you want to keep loading AX with the whole 16bit words, increment SI by 2 (ADD SI,2).

You could also replace both MOV AX,[SI] and ADD SI,2 with one single instruction LODSW which does the same and occupies only one byte instead of five. In this case you should be sure to have the Direction flag reset (using the instruction CLD in the beginning of your program).

  • Related