Arrays and Pointers


Consider the following C code segment:

        /* Copy numVals values from A into B */
        int i;
        for ( i = 0; i < numVals; i++ )
            B[i] = A[i];


This can be written using array indexing or pointers.

Using Array IndexingUsing Pointers
/* Copy numVals values from A into B */
int i;
for ( i = 0; i < numVals; i++ )
    B[i] = A[i];
/* Copy numVals values from A into B */
int * ptrA, * ptrB;
for ( ptrA = A, ptrB = B; ptrA < A + numVals;
      ptrA++, ptrB++ )
        *ptrB = *ptrA;


MIPS translation using array indexing:

C Array IndexingMIPS Equivalent
/* Copy numVals values from A into B */
int i;
for ( i = 0; i < numVals; i++ )
    B[i] = A[i];

        move $t0, $zero
LOOP:   slt $t1, $t0, $a2
        beq $t1, $zero, ENDLP
        sll $t2, $t0, 2
        add $t3, $a0, $t2
        add $t4, $a1, $t2
        lw  $t5, 0($t3)
        sw  $t5, 0($t4)
        addi $t0, $t0, 1
        j LOOP
ENDLP:  ...
# $a0 = A, $a1 = B, $a2 = numVals
# $t0 = i = 0
# $t1 = 1 if i < numVals
# leave loop if i >= numVals
# $t2 = 4 * i
# t3 = A + 4i, i.e., &A[i]
# t4 = B + 4i, i.e., &B[i]
# read A[i] into $t5
# store $t5 out to B[i]
# increment i
# jump to top of loop


MIPS translation using pointers:

C PointersMIPS Equivalent
/* Copy numVals values from A into B */
int * ptrA, * ptrB;
for ( ptrA = A, ptrB = B; ptrA < A + numVals;
      ptrA++, ptrB++ )
        *ptrB = *ptrA;

        move $t0, $a0
        move $t1, $a1
        sll $t2, $a2, 2
        add $t2, $a0, $t2
LOOP:   slt $t3, $t0, $t2
        beq $t3, $zero, ENDLP
        lw  $t4, 0($t0)
        sw  $t4, 0($t1)
        addi $t0, $t0, 4
        addi $t1, $t1, 4
        j LOOP
ENDLP:  ...
# $a0 = A, $a1 = B, $a2 = numVals
# $t0 = ptrA = A  (or &A[0])
# $t1 = ptrB = B  (or &B[0])
# $t2 = 4 * numVals
# $t2 = A + 4 * numVals
# $t3 = 1 if ptrA < A + 4*numVals
# leave loop if ptrA >= A + 4*numVals
# read *ptrA into $t4
# store $t4 out to *ptrB
# increment ptrA  (by 4 because ptr to int)
# increment ptrB  (by 4 because ptr to int)
# jump to top of loop
# after loop, return to address in $ra


Alyce Brady, Kalamazoo College