如何使用指针访问程序集中的数组中的整数?

时间:2015-07-04 05:49:32

标签: assembly x86

首先,这是一项家庭作业。有人告诉我使用push和pop创建一个带有这些参数的排序函数。它们在这样的函数中传递,我不知道如何使用“int * list”访问其中的元素。我正处于这个过程的中间

    int sorter (int* list, int count, int opcode)
    {
    __asm
    {
   mov eax, 0; zero out the result
   mov ebx, opcode; move opcode to ebx for comparison
   ; fill in your code here
   mov ecx, 0; set the counter to 0
   cmp ebx, 0x01; check ascendant or descendant
   je ASCENDANT
   jne DESCENDANT
   ASCENDANT:
   loop_start :
   cmp ecx, count; condition for the outer loop
   jge loop_end
   push ecx
   mov eax,
   }
   }



 loop_start:
   cmp ecx, count   ; condition for the outer loop
   jge loop_end     ; jump if end of array
   mov esi, list    ; move pointer to esi
   mov eax, [esi + 4 * ecx] ; move data that current index to eax
   push ecx         ; push ecx to the stack to save the index
   inner_loop:
     inc ecx        ; increment eax
     cmp eax, [esi + 4 * ecx]; compare eax with the next element in the array
     jle swap       ; if it is less than the current value than jump to swap
     cmp ecx, count ; check if ecx reaches the end of array
     jle inner_loop ; if not than go back to inner loop
     pop ecx        ; it ecx reaches the end than pop eax to go back to the old index of outer loop
     mov[esi + 4 * ecx], eax ; exchange the value of current eax to the element that is compared
     inc ecx        ; increment ecx for outer loop
     jmp loop_start ; jump back to loop start
     swap:          ; swap the smaller value with the current value
     mov eax, [esi + 4 * ecx] ; swapping
   jmp inner_loop   ; jump back to inner loop
 loop_end:
 ret

2 个答案:

答案 0 :(得分:2)

list的值(即int s的地址)放在寄存器中,并使用寄存器间接寻址:

mov esi, list   
mov eax, [esi]  ; read the first element
mov eax, [esi+4]  ; read the second element
add esi, 8  ; move 2 elements ahead
mov eax, [esi]  ; read the third element
; etc...

如果要交换ecxedx中索引指定的数组中的两个元素,您可以这样做:

mov eax, [esi + ecx*4]    ; eax = elem1
xchg eax, [esi + edx*4]   ; swap eax and elem2
mov [esi + ecx*4], eax    ; elem2 = old elem1

答案 1 :(得分:2)

x86 CPU支持索引寻址,如:

mov edx, list                      ;edx is a list ptr
mov ecx, index                     ;ecx ia an array index 
mov eax, dword ptr[edx + ecx * 4]  ;Load result to eax