Assigning / Printing values to void * in a structure

2
#include <stdio.h>

typedef struct elem{

    void * d;

}Elem;

main(){

    Elem *p;
    Elem e;

    double pi = 3.14;

    e.d = &pi;
    p->d = &pi;

    printf("%f\n",p->d);
    printf("%f\n",e.d);


}

When I do the printf , the values in stdout are completely different from the value that you assign to the pointer to void .

How can I resolve this?

    
asked by anonymous 28.01.2016 / 20:40

1 answer

2

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 = &pi;
    p->d = &pi;

    printf("%f\n", *((double *)p->d));
    printf("%f\n", *((double *)e.d));
    return 0;
}

See running on ideone .

    
28.01.2016 / 21:19