# Arrays and Pointers

### Consider the following C program:

 ```int main(int argc, char * argv[]) { int sum; int Y[20], Z[20]; ... /* Assume Y gets filled with values */ copy(Y, Z, 20); ... } ``` ```/* Copy numVals values from A into B */ void copy(int A[], int B[], int numVals) { int i; for ( i = 0; i < numVals; i++ ) B[i] = A[i]; return; } ```

### Copy function can be written using array indexing or pointers.

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

### Copy function using array indexing:

C Array IndexingMIPS Equivalent
```/* Copy numVals values from A into B */
void copyArrInd(int A[], int B[], int numVals)
{
int i;
for ( i = 0; i < numVals; i++ )
B[i] = A[i];
return;
}
```
```copyArrInd:
move \$t0, \$zero
LOOP:   slt \$t1, \$t0, \$a2
beq \$t1, \$zero, ENDLP
sll \$t2, \$t0, 2
lw  \$t5, 0(\$t3)
sw  \$t5, 0(\$t4)
j LOOP
ENDLP:  jr \$ra
```
```# \$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]
# store \$t5 out to B[i]
# increment i
```

### Copy function using pointers:

C PointersMIPS Equivalent
```/* Copy numVals values from A into B */
void copyPtrs(int * A, int * B, int numVals)
{
int * ptrA, * ptrB;
for ( ptrA = A, ptrB = B; ptrA < A + numVals;
ptrA++, ptrB++ )
*ptrB = *ptrA;
return;
}
```
```copyPtrs:
move \$t0, \$a0
move \$t1, \$a1
sll \$t2, \$a2, 2
LOOP:   slt \$t3, \$t0, \$t2
beq \$t3, \$zero, ENDLP
lw  \$t4, 0(\$t0)
sw  \$t4, 0(\$t1)
j LOOP
ENDLP:  jr \$ra
```
```# \$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