1

I'm new to MIPS assembly and I'm trying to learn how to use arrays. I understand that arrays are declared in the .data segment and then you load the address of the array to the register. However, I'm confused on accessing elements of the the array and changing the values. Here is a simple program I wrote in C that I'm trying to convert into assembly. Any explanation/code is greatly appreciated!

void addArray (int arrA[], int arrB[], int i, int j) {
    arrB[j] = arrA[i] + arrA[i + 1];
    printf("%d", arrB[j]);
}

int main(void) {
    int arrA [] = {1,2,3,4,5,6};
    int arrB [] = {1,1,1,1,1,1};
    int i = 2;
    int j = 3;

    addArray(arrA, arrB, i, j);

    return 0;
}
Ayelir
  • 41
  • 1
  • 1
  • 6
  • You'd use the appropriate load and store instructions. I assume that you've already downloaded the MIPS instruction set reference so that you can look those up. What exactly is unclear? – Michael Oct 18 '19 at 06:56
  • The arrays have `int` elements. So, indexing `a[i]` means computing `a+i*4` and using that address with a load if you need the value at that location or store to update the value at that location... – Erik Eidt Oct 18 '19 at 14:08

1 Answers1

-1

Try this code

    .data
    arrA: .word 1,2,3,4,5,6
    arrB: .word 1,1,1,1,1,1


.text

.globl main

main:
    la $a0,arrA   #load address of arrA into $a0 register (first parameter)
    la $a1,arrB   #load address of arrB into $a1 register (second parameter)

    li $a2,4      # load $a2 register with 3 (threeth parameter)
    li $a3,3      #  load $a3 register with 3 (fourth parameter)

    jal addArray  # call addArray function

    exit:         # syscall to exit the programm
        li $v0, 10   
        syscall
addArray:

    addi $sp,$sp,-4         #allocate space in stack
    sw $ra,0($sp)

    move $t0,$a2            #copy a content of $a2 register into $t0 
    move $t1,$a3            #copy a content of $a3 register into $t1

    mulu $t0,$t0,4          # multiplication by 4 with the value of $t0, because each number have 4 bytes as offset

    addu $a0,$a0,$t0        # 

    lw $t3,($a0)            # arrA[i]
    addi $a0,$a0,4          #  i+1

    lw $t4,($a0)            # arrA[i+1]

    add $t5,$t3,$t4         #   arrA[i] + arrA[i + 1]
    mul $t1,$t1,4           #  j 
    addu $a1,$a1,$t1      
    sw $t5,($a1)            #     arrB[j] = arrA[i] + arrA[i + 1];



print_out:
    lw $s0,($a1)
    li $v0, 1       #print the input number
        move $a0, $s0
        syscall 

        lw $ra,0($sp)      # free stack and return to main
    addi $sp,$sp,4
    jr $ra
nissim abehcera
  • 821
  • 6
  • 7