I have two functions here that I've written and tested. Both do exactly the same thing - calculate the length of a string - but they use two different methods:
Accessing through indexes:
int strlength( char arr[] ){
int length = 0;
for( int i = 0;; i++ ){
if( arr[i] > 0 ){
// if not the end of the string
length++;
}
else{
break;
}
}
return length;
}
Accessing through pointers:
int strlength( char arr[] ){
int length = 0;
char *arrptr;
arrptr = &arr[0];
for( int i = 0;; i++ ){
if( *(arrptr + i) > 0 ){
length++;
}
else{
break;
}
}
return length;
}
Apparently, the second version of the function will be faster because it uses pointers to access the array elements rather than accessing them through their indexes. I can understand why this would be, as pointers are closer to the hardware and there is no need for the program to calculate the address based on the index.
Do you think this is an accurate assessment?


Sign In
Create Account


Back to top









