>I thought that this would be a way out, but there are no pointers there.
Ah, but there are pointers, you just can't see them. This is the equivalent function with pointer notation (what those nice little [] operators hide from you) and the problems fixed:
Code:
int sum_array ( int *array, int size )
{
int i, total_sum = 0;
for ( i = 0; i < size; i++ )
total_sum += *(array + i);
return total_sum;
}
This is a reasonable implementation if you must use pointers, but I think your problem is that you must use pointers in place of the i variable. The only safe way is to have a sentinel value at the end of the array, declared like this:
int a[6] = { 1, 2, 3, 4, 5, -1 };
And the function could be modified like so:
Code:
int sum_array ( int *array )
{
int *i, total_sum = 0;
i = array;
while ( *i != -1 ) {
total_sum += *i;
++i;
}
return total_sum;
}
-Prelude