Ankky Ankky - 13 days ago 8
C Question

Newbie in C - wrong return type

I have a function similar to this using pointers in C

float *compute_avg(float *array, int num_elements) {
float sum = 0.f;
int i;
for (i = 0; i < num_elements; i++) {
sum += array[i];
}
return sum;
}


But error occurs "return value type does not match function type".

Answer

It's because your function returns a float *, and you're trying to return a float. You can just remove the * to change the first line to float compute_avg(float *array, int num_elements)

You can also declare sum as a float * and then malloc memory for it. Then you should use *sum += array[i];, but remember to free it later.

Comments