Help with function

Pat Myrto pat at rwing.UUCP
Mon Jan 8 06:37:07 AEST 1990


In article <3198 at cbnewsj.ATT.COM>, veenu at cbnewsj.ATT.COM (veenu.r.rashid) writes:
> 	On the compiler I'm using, abs() and strtol() seem to generate incorrect
> or at least inaccurate results.  I'm using the following code:
> 
> ---
> main(int argc, char *argv[])
> {
> 	double temp;
> 
> 	temp = strtod(argv[1]);		/* get the argument as a double	*/
> 	printf("Absolute value of %g is %g\n", temp, abs(temp));
> }
> 
> ---
> 
> The program produces truly screwy output at the least
> provocation.  The strange thing about it that the

Your problem is incorrect usage of strtod().  First, it takes a second
argument, a pointer to a string pointer, which will contain the point
where strtod stops its scan.  Present code will write this to some
undefined place.  But the reason you got screwey output, is because the
compiler thinks strtod() returns an INTEGER (int), because nobody told
it different.

Change the line "double temp;" to "double temp, strtod();" and the
results will be better.  The output from strtod() was treated as an
int, and then cast to double by the compiler.  Shoving a double
through an int almost always mangles it.  But also add in the
variable definitions a "char *stopstr;" or somthing like that, and
call strtod() like

    temp = strtod(argv[1], &stopstr);

Because not doing so will corrupt something else in your data space,
causing a hard-to-find bug in a real program.

I verified the above by copying the code, compiling it, and running
it.  Adding the declaration that strtod() returns a double fixed it.

-- 
pat at rwing                                       (Pat Myrto),  Seattle, WA
                     ...!uunet!pilchuck!rwing!pat
             ...!uw-beaver!sumax!polari!/
WISDOM:    "Travelling unarmed is like boating without a life jacket" 



More information about the Comp.lang.c mailing list