Why can I calculate the number of elements in array foo with sizeof(foo)/sizeof(foo[0]), but if I use the same calculation inside the functions squares_calculator I keep getting 1 as the length?
I just want to ask if my understanding is correct based on the code below. This is a solution posted to a homework problem by my prof.
So the function below takes in two pointers, one points to the start of the array, the other points to one past the last element of the array. "double result" will be used to add the absolute values of each element in the array.
To access the elements in the array we start with "start" to access the first element, then to access the next one, we use "start++" which means we now look at the next element in the array and keep incrementing "start" until we get to just one before the "end" pointer. At this point the bool statement in the while loop is now false, then "result" is returned.
1 2 3 4 5 6 7 8 9 10 11 12 13
double sum_of_elements_of_an_array(double* start, double* end) {
double result = 0.0;
while (start < end) {
result += abs(*start);
start++;
}
return result;
}
int main(){
double foo [3] = {1.3,2.4,3.5};
sum_of_elements_of_an_array(foo, foo + 3);
}
It also depends whether the array you are passing has a termination element. For instance if you terminate an array of positive integers with -1, then the size of the array is not required, just test for -1. Or count up to terminator if you need the array's size once it's been passed.