Assign/Print values to void * in a structure

Asked

Viewed 66 times

3

#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 you assign to the pointer for void.

How can I fix this?

  • 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]

  • 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.

1 answer

3

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

  • thank you very much! really this is an exercise I have done apart, to try to realize the problem with Linked List ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.