I've been given a problem in which I have to write a function that accepts two parameters (both are pointers, the first one points at the beginning of an array and the second one points to the place in memory after the last element of the array)
The function has to be called from the first element of the array to the one in the middle, and then from the middle element to the one at the end, and then the function should return the value of those two which is bigger.
double max_element(double *p1, double *p2)
{
double from_first_to_middle = max_element(p1, (p1 + p2) / 2 + p1);
double from_middle_to_last = max_element((p1 + p2) / 2 + p1, p2);
if(from_first_to_middle > from_middle_to_last)
{
return from_first_to_middle;
}
else
{
return from_middle_to_last;
}
}
But when I try to run this code it gives me the error
error: invalid operands to binary + (have ‘double *’ and ‘double *’)
So then I thought that I should dereference these pointers as I cannot do these operations with the addresses they point to, but it still does not work.
Can anyone help?
Thanks!
p1+(p2-p1)/2instead, as here the second operand for addition will have an integer type (ptrdiff_t).p1 == p2means empty,p1 + 1 == p2means single item, sop2 - p1yields 1 althoughp2is pointing outside the array. Unless you dereference it, it isn't UB.