rondino rondino - 4 months ago 13
C Question

modf function intpart is zero?

What am I doing wrong I always get

intpart
equal to
0
when I enter any number ?

#include <stdio.h>
#include <math.h>

int main(int argc, char* argv[])
{
double x=0.,fraction=0.;
int intpart=0;
printf("read value of x :");
scanf("%lf",&x);
fraction=modf(x,&intpart);
printf("x=%f intpart=%d fraction=%f \n",x,intpart,fraction);
return 0;
}

Answer

modf() takes double* as its second argument. But you are passing an int*. So, it's undefined behaviour. The solution is to use a double*:

Change

int intpart=0;

to

double iptr = 0;

Compile with all warnings enabled. Clang produces the warning:

warning: incompatible pointer types passing 'int *' to parameter of type 'double *' [-Wincompatible-pointer-types]

and gcc produces:

warning: passing argument 2 of ‘modf’ from incompatible pointer type [-Wincompatible-pointer-types]

See C11 draft, 7.12.6.12, The modf functions.

Comments