It's really not that simple. The first error is that you did not initialize the object by pointing to p
. The way it usually does is not very useful, but I understand it to be an exercise. You have to boot into stack , as I did below, or in heap , as it is most useful.
Then you have to cast cast when you get the value. You probably already know that this is a way of storing any value, it's a way of giving a type dynamism to the language. Of course this comes at a price. The code becomes unsafe. You need to know a lot what you're doing. If you use the right options to compile, the compiler itself does not let the wrong way. And that's good. Everyone should compile codes with all linked warnings .
I have still modified to adopt main()
in default form:
#include <stdio.h>
typedef struct elem {
void * d;
} Elem;
int main() {
Elem *p = &(struct elem) { .d = NULL }; //malloc(sizeof(Elem));
Elem e;
double pi = 3.14;
e.d = π
p->d = π
printf("%f\n", *((double *)p->d));
printf("%f\n", *((double *)e.d));
return 0;
}
See running on ideone .