7. Using a pointer to access an array
When an array is passed as a function argument,only the starting address of the array is passed,
and the function receives this address in a pointer variable
which can be used as a local variable inside the function.
For example, rewriting strlen using pointer access instead of array indexing:
size_t strlen( const char *s) { size_t len = 0; while( *s != '\0') { ++len; ++s; } return len; }Alternatively, the string length can be computed by subtracting pointers to the beginning and end of the string:
size_t strlen(const char *s) { const char *start = s; while( *s != '\0') ++s; return s - start; }Functions which operate on arrays of int or double can also be written using pointer access.
For example, for the sum of an array of double:
double sum( const double x[], int n) /* x is `const double *' */ { double r = 0; while( n > 0) { r += *x; --n; ++x; /* ++x adds 1 * sizeof(double) */ } return r; }