an elementary question concerning double indirection

John S. Price john at stat.tamu.edu
Mon Feb 26 00:29:33 AEST 1990


In article <8146 at hubcap.clemson.edu> kaires at hubcap.clemson.edu (Robert G Kaires) writes:
>Dear C users:
>
>[...stuff deleted...]
>why 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)?
The reason is this:  you send this function the address of a character pointer,
and it changes the pointer to point to the place in the string where the
error occurs.  For example:

...
char *error, *string = "10.2#4";  /* or whatever you like */
double num;

num = strtod(string, &error);
...

Pass the address of the pointer that you want to point to the error.
That's is why it's declared as a char **.  You have a character pointer,
and you are taking the address, thus a pointer to a character pointer, which
is a char **.

>Unfortunately the description of double indirection is poorly explained
>in my manuals, and no description of how to use this function is given.

There is nothing special about double indirection, although I have
to admit that I was a little confused when I first started working
with it.  Just think of it this way.  When you apply the indirection
operator (*foo), you are looking at what "foo" points to.  This can
be any valid data type, that being an integer, float, structure, or
pointer.  If it's a pointer, well, you dereference it again to get
what it's pointing to.  It's actually quite simple once you catch
on to it.  I've had programs where I've had up to 5 levels of indirection,
something like a pointer to an array of pointers to functions returning
a pointer to a structure, or something like that. 

>However, I plunged ahead and tried to use it anyway. Here is my short 
>program:
>
>#include <math.h>
>#include <stdio.h>
>#include <string.h>
>#include <stdlib.h>
>
>main()
>{
>char string[30]={""};
>char **ptr;
>double ans;
>clrscr();
>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);
>   }
>}
Just change the "char **ptr" to a "char *ptr", and change the
call to strtod(string, ptr) to strtod(string,&ptr).
That SHOULD work, although I haven't tested it.

Hope that made sense, and helps any.

>Bob Kaires 


--------------------------------------------------------------------------
John Price                   |   It infuriates me to be wrong
john at stat.tamu.edu           |   when I know I'm right....
--------------------------------------------------------------------------



More information about the Comp.lang.c mailing list