简体   繁体   中英

Simple Array Manipulation MIPS Assembly

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM