Arrays and Pointers


Consider the following C code segment:

        /* Double every value in A */
        int i;
        for ( i = 0; i < numVals; i++ )
        {
            A[i] *= 2;      /* i.e., A[i] = A[i] * 2 */
        }


This can be written using array indexing or pointers.

Using Array IndexingUsing Pointers
/* Double every value in A */
int i;
for ( i = 0; i < numVals; i++ )
{
    A[i] *= 2;      /* i.e., A[i] = A[i] * 2 */
}
/* Double every value in A */
int * ptrA;
for ( ptrA = A; ptrA < A + numVals; ptrA++ )
{
    *ptr *= 2;      /* i.e., *ptr = *ptr * 2 */
}


MIPS translation using array indexing:

CMIPS Equivalent
/* Double every value in A */
{ /* A[i] = A[i] * 2 */ int x = A[i]; x *= 2; A[i] = x;
        # $s6 = A, $s7 = numVals
        # $t0 = i, $t4 = x
        addi $t0, $zero, 0
LOOP:   slt $t1, $t0, $s7
        beq $t1, $zero, ENDLOOP

        # Calculate address of A[i]
        sll $t1, $t0, 2
        add $t1, $s7, $t1
        # Read value at A[i] into x; etc
        lw  $t4, 0($t1)
        sll $t4, $t4, 1
        sw  $t4, 0($t1)

        addi $t0, $t0, 1
        j LOOP
ENDLOOP:
        ⋮ 


# $t0 = i = 0
# $t1 = 1 if i < numVals
# Leave loop if i >= numVals


# $t1 = 4 * i (shift left 2)
# t1 = A + 4i, i.e., &A[i]

# Read A[i] into $t4 (x)
# x *= 2 (shift left 1)
# Store $t4 out to A[i]

# Increment i
# Jump to top of loop

MIPS translation using pointers:

CMIPS Equivalent
/* Double every value in A */

{ /* A[i] = A[i] * 2 */ int x = A[i]; x *= 2; A[i] = x;
        # $s6 = A, $s7 = numVals
        # $t0 = ptrA, $t9 = A + numVals
        # $t4 = x
        add $t0, $s6, $zero
        sll $t9, $s7, 2
        add $t9, $t9, $s6
LOOP:   slt $t1, $t0, $t9
        beq $t1, $zero, ENDLOOP

        # Read value at *ptr into x; etc
        lw  $t4, 0($t0)
        sll $t4, $t4, 1
        sw  $t4, 0($t0)

        addi $t0, $t0, 4
        j LOOP
ENDLOOP:
        ⋮ 



# $t0 = ptrA = A
# $t9 = 4 * numVals
# $t9 = pastA = A + 4 * numVals
# $t1 = 1 if ptrA < pastA
# Leave loop if ptrA >= pastA


# Read *ptrA into $t4 (x)
# x *= 2 (shift left 1)
# Store $t4 out to *ptrA

# Increment ptrA
# Jump to top of loop

Alyce Brady, Kalamazoo College