# Pointers and arrays

I just started to learn pointers, so I'm interested if I used them correctly in this task where I check if the absolute value of the greatest element in an array is two times greater than the absolute value of the smallest one.

My code works properly; I'm just interested if I used the pointer correctly (it should only be used for an array).

    #include <stdio.h>
#include<math.h>
int minmax2x(float* array, int size){
double min=array[0],max=array[0];
int i;
for(i=0;i<size;i++){
if(array[i]<0)
array[i]=array[i]*(-1);
}
for(i=0;i<size;i++){
if(array[i]>max)
max=array[i];
if(array[i]<min)
min=array[i];
}
if(max>2*min)
return 1;
else return 0;
}

int main() {
float array1[5] = { 5.5, 6.6, -7.7, -6.6, -5.5};
float array2[5] = { 3.3, 2.2, 1.1, 2.2, 3.3};
int res1 = minmax2x(array1, 5);
int res2 = minmax2x(array2, 5);
printf("%d %d", res1, res2);
}


• Welcome to Code Review! Please edit your question so that the title describes the purpose of the code, rather than its mechanism. We really need to understand the motivational context to give good reviews. Thanks! Commented Jan 17, 2021 at 10:27

Your pointer usage is fine, but there are some other oddities in the code. Floats get assigned to doubles for no discernable reason. There exists an entire loop to make an array positive, which can be accomplished using abs(). There exist multiple return statements which can be reduced to a single expression.

A more notable issue is tht the absolute conversion occurs AFTER the default values for min and max have been set. This means that a negative value at the start of an array can leak into min and affect results. For example, consider the array (-2,1). Clearly, the absolute maximum is not greater than 2 times the absolute minimum. Yet, your code returns 1 for this case. This critique is working off the assumption that the code's intended purpose is to determine max(abs(x)) > 2*min(abs(x))

Here is how I would write this code:

int minmax2x(float* array, size_t size){
float min = abs(array[0]);
float max = abs(array[0]);

for(size_t i=1; i<size; ++i){
float val = abs(array[i]);
if(val>max) max=val;
if(val<min) min=val;
}
return max > 2*min;
}

• I always forget we have the type-generic abs() since C99. I grew up with fabs(), fabsf() and fabsl() and still turn to those, so thanks for the reminder! Commented Jan 17, 2021 at 10:32