C array indexing in MIPS assembly?

前端 未结 1 807
刺人心
刺人心 2021-01-29 14:46

Question:

void swap (int v[], int k)
{
int temp;
temp = v[k];
v[k] = v[k+1];
v[k+1] = temp;
}

My question is why does int v[] get

相关标签:
1条回答
  • 2021-01-29 15:18

    whoever did this didn't even comment it so I'm assuming $a0 is v[] and $a1 is k

    These are the MIPS calling conventions. First 4 arguments of a function are in $a0..$a3 and return value (not required here) is in $v0 (and $v1 if required). Return address is in register $ra.

    I know this is used to swap variables but what is it doing here, why is it adding v[] with k? isnt v[] a array of declared variables, how can you add it with a integer k?

    v[] is indeed an array of int. What holds variable v is the address of the array. Adding a value to an array address is the way to go to specific elements of the array.

    swap:                   # void swap (int v[], int k)
                            ; so v[] is in $a0 and k in $a1
          sll $t1, $a1, 2   ; k*=4 (ie sizeof(int))
          add $t1, $a0, $t1 ; $t1=@v+4*k==@(v[k])
          lw $t0, 0($t1)    #   temp = v[k];
          lw $t2, 4($t1)    ; 4(t1) is @(v[k])+4==@(v[k+1]
                            ; $t0==temp==v[k], $t2==v[k+1]
          sw $t2, 0($t1)    #   v[k] = v[k+1]; 
          sw $t0, 4($t1)    #   v[k+1] = temp;
          jr $ra            ; go back to caller
    
    0 讨论(0)
提交回复
热议问题