casting ints and floats to char*
Dale Worley
worley at compass.com
Fri Apr 26 00:47:33 AEST 1991
In article <6185 at mahendo.Jpl.Nasa.Gov> robert at nereid.jpl.nasa.gov (Robert Angelino) writes:
void has_to_be_done_this_way()
{
char *ptr[12];
int i;
long j;
double p;
ptr[0] = &i;
ptr[1] = &j;
ptr[2] = &p;
sscanf(buf,"%2d %5ld %15lf",&(*ptr[0]),&(*ptr[1]),&(*ptr[2]));
}
Better would be to define ptr as an array of void *, since that's
the new convention for "generic pointer". (char * will also work, and
you have to use it if your compiler doesn't support void *, but it
doesn't protect you from accidentally dereferencing the pointer.)
Second, &(*ptr[0]) is equivalent to ptr[0].
But you don't want to say that, because sscanf wants three pointer
arguments: int *, long *, and double *, each of which may be
represented in a different manner than char * or void *. What you
want to say is:
sscanf(..., (int *)ptr[0], (long *)ptr[1], (double *)ptr[2]);
Always cast your generic pointers back to the right types before using
them to access data.
Dale
Dale Worley Compass, Inc. worley at compass.com
--
"Bob" sold it. I bought it. That settles it. -- <_Jym_R_Dobbs_>
More information about the Comp.lang.c
mailing list