CS232 Lecture 5 Notes
Pointers:
In previous lectures, we've seen how to do array indexing, but if
we're looping through arrays sometimes it is more efficient to use
pointer arithmetic. For example, the strlen function, which
measures the length of a string by searching for the zero that
terminates the string, can be implemented in the following two ways:
Array Version: Pointer Version: Optimized Pointer Version:
int strlen(char *str) { int strlen(char *str) { int strlen(char *str) {
int length = 0; int length = 0; char *temp = str;
while (str[length] != 0) { while (*str != 0) { while (*temp != 0) {
length ++; str ++; temp ++;
} length ++; }
return length; } return (temp - str);
} return length; }
}
strlen: strlen: strlen:
li $v0, 0 li $v0, 0 move $v0, $a0
l: add $t0, $v0, $a0 l: lb $t0, 0($a0) l: lb $t0, 0($v0)
lb $t0, 0($t0) beq $t0, $0, e beq $t0, $0, e
beq $t0, $0, e
add $a0, $a0, 1 add $v0, $v0, 1
add $v0, $v0, 1 add $v0, $v0, 1 j l
j l j l
e: sub $v0, $v0, $a0
e: jr $ra e: jr $ra jr $ra
When dealing with arrays of ints (or anything larger than bytes) the array index no longer equals the address offset, so we need an additional instruction to scale the array index, e.g.,
mul $t0, $v0, 4
add $t0, $t0, $a0
lw $t0, 0($t0)
For non-byte arrays, the str ++ statement (or temp ++) has to add the size
of the data item (instead of always 1) to the pointer. For example, the pointer increment
for an array of integers would be:
add $v0, $v0, 4