Hans Ginzel wrote:
Hello,
let us consider function
int foo(char *name, void *data) {
...
printf(name, data); /* Should be *data? */
...
}
and calling
double epsilon=1e-5;
foo("epsilon: %lg\n", &epsilon);
By the way, "%lg" and "%g" mean the same thing to
printf(); the "l" has no effect.
Function foo could change data, sopointer is needed.
Data could be of different type (int, double, long int),
but always is passed corresponding format (%...) for printf in `name'.
How to program this correct? How to correct dereference variable `data'?
gcc warns about derefencing void variable.
Or how to say it to printf, that it should dereference it's argument?
There is no easy way to do exactly what you ask.
You will need to parse the `name' string to find out
what data type is needed, and then convert `data' to
a pointer to that type before de-referencing it. In
pseudocode:
if (name needs a double)
printf (name, *(double*)data);
else if (name needs an int)
printf (name, *(int*)data);
else if (name needs a long int)
printf (name, *(long int*)data);
else ...
It might be better (and would certainly be easier)
to change the signature of the foo() function to be
more like that of printf() itself:
int foo_new(char *name, ...) {
va_list ap;
va_start (ap, name);
vprintf (name, ap);
va_end (ap);
...
}
Note that this change also requires a change in the way
you call the function:
double epsilon = 1e-10;
foo ("epsilon = %g\n", &epsilon);
foo_new ("epsilon = %g\n", epsilon);
(Observe that foo_new() takes the *value* of epsilon, not
a pointer to it.)
--
Er*********@sun.com