Karl Joonas Volke Karl Joonas Volke - 1 year ago 74
C Question

Two or more values from function in C

Im trying to get 2 values from a function. I've googled the problem, but I seem to mess up the code myself.

double* suurim(double arv[], int x, double *array)
int i;
double temp;
temp = arv[0];
for(i = 1; i < x; i++) // biggest
if (arv[i] > temp)
array[0] = arv[i];
for(i = 1; i < x; i++) // smallest
if (arv[i] < temp)
array[1] = arv[i];
return array;

suurim(arv, mituArvu, array);
printf("%0.1lf\n", array[0]);

It does not return what it's supposed to. What is going on here?

There is an array Arv. The function should get the biggest and smallest number from the array Arv and put them to array[0] and array[1] respectively.

edit This i probably a duplicate, but other questions answers contain structures, which I don't want.

Answer Source

Your approach is a valid way of returning more than one value back from a function. But:

For your maximum, you are merely returning the element of the array with the greatest index that is larger than the first element. (temp does not change once set). That's an algorithmic failure: e.g. your_max(1, 3, 2, 0) would return 2.

You don't actually need temp: you can compare arv[i] > array[0], having initialised array[0] to arv[0].

Ditto for the the computation of the minimum.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download