I have written this function to calculate the average of some floats.But it has a runtime error at the last line of the while in “average” function.What’s the problem with it?
#include <stdarg.h>
#include <stdio.h>
float average(float first , ...)
{
int count = 0;
float sum = 0 , i = first;
va_list marker;
va_start(marker , first);
while(i != -1)
{
sum += i;
count++;
i = va_arg(marker , float);
}
va_end(marker);
return(sum ? (sum / count) : 0);
}
int main(int argc , char* argv[])
{
float avg = average(12.0f , 34.0f);
printf("The average is : %f\n" , avg);
scanf("a\n");
}
You forgot to end the call with a
-1, so yourwhileloop causes undefined behaviour because it tries to keep getting more arguments than you passed. It should be:Also,
floatarguments are promoted todoublewhen being passed to variadic functions, so you can’t usefloatwithva_arg. You should be usingdoublefor all this: