an elementary question concerning double indirection

Rich Walters raw at math.arizona.edu
Tue Feb 27 13:47:06 AEST 1990


In article <8146 at hubcap.clemson.edu> kaires at hubcap.clemson.edu (Robert G Kaires) writes:
> this function has the syntax:
>             double strtod(const char *s, char **endptr);
>
>Why is endptr a pointer to a pointer (and not just a pointer)?
>Unfortunately the description of double indirection is poorly explained
>in my manuals, and no description of how to use this function is given.
>However, I plunged ahead and tried to use it anyway. Here is my short 
>program:
>
>char string[30]={""};
>char **ptr;
>double ans;
>
>while(1)
>   {
>   gets(string);
>   if (*string == 'q') break;
>   ans=strtod(string,ptr);
>   if ( ( string+strlen(string) ) != *ptr )   /* <--- warning here  */
>      printf("format error\n");
>   else
>      printf("You typed the number: %f\n",ans);
>   }
>}
>This program seems to work OK (try it). However I do get warnings on the
>line indicated that "I am trying to use ptr before it is defined". Even
>worst, when I use this fragment in a much larger program, all hell
>breaks loose. It seems that I am writing over sections of memory that
>belong to other varaiables. Please tell me what is wrong.

The reason you get the warning is obvious.  ptr has not been (explicity) 
assigned a value.  You will get this warning whenever a variable is initialized
in a standard function.

A better way might be

#include <stdio.h>
/* other appropriate includes */

main()
{
  char string[30];
  char *ptr;
  double ans;
  extern double strtod();
  
  while(1) {
    gets(string);
    if (*string == 'q') break;
    ans=strtod(string,&ptr);
    if ( ( string+strlen(string) ) != ptr )   /* <--- warning here  */
      printf("format error\n");
    else
      printf("You typed the number: %f\n",ans);
  }
}


This works.  strtod wants to modify ptr to point to the correct place.  thus
you must send it the address of (a pointer to) the pointer that is to point to
the terminating character.  On my machine if I send it 12.34abcde, ptr points
to the 'b'. I'm not sure why.


				Richard Walter

-------------------------------------------------------------------------------

			Keep on crunching those numbers

-------------------------------------------------------------------------------



More information about the Comp.lang.c mailing list