It’s really not very simple. The first error is that you didn’t initialize the object by pointing to p
. The way normally used is not very useful, but I understand that it is an exercise. You have to initialize in stack, as I did below, or in the heap, how is most useful.
Then you have to make one cast when you take the amount. You probably already know that this is a way to store any value, is a way to give a dynamism of types to language. Of course, this comes at a price. The code is insecure. You need to know a lot what you’re doing to work. If you use the right options to compile, the compiler does not pass the wrong way. And that’s good. Everyone should compile codes with all the warnings connected.
I still modified it to adopt the main()
in standard 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));
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Can you already accept the answer in this one too? After accepting you will be able to vote on everything on the site too, which is different from accepting. See the [tour]
– Maniero
Did the answer solve the problem? Do you think you can accept one of them? See [tour] how to do this. You’d be helping the community by identifying the best solution. You can only accept one of them, but you can vote for anything on the entire site.
– Maniero