This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

void pointer to struct pointer cast

I declared a void pointer

void *ptr;

and a typedef struct named testStructure, with a member 'unsigned int a'.

Now I will cast this pointer to a struct pointer:

ptr=(testStructure*)malloc(sizeof(testStructure));

Now I try to access the member of the struct...

ptr->a=5;

...and I get an error "expression must have a pointer-to-struct-or-union type"...
Why is 'ptr' still void? It seems, a void pointer cannot be casted to any other pointer type...
How I can do this properly?
I just need ONE pointer, which can point to different structures, that means, I need to cast a void pointer...

Parents
  • It doesn't work like that!

    For a start, if you want a pointer to that structure, why don't you just define it as a pointer to that structure:

    testStructure *ptr;
    

    The type given for a variable in its declation or definition is fixed; if you declare ptr as a pointer to void, then it will always be a pointer to void.
    If you want to use it as a pointer to something else, then you have to cast it at the point that you use it.

    So the cast in your mallo statement is pointless; the cast should come when you reference the pointer:

    ptr = malloc( sizeof(testStructure) );
    

    ((testStructure*)ptr)->a = 5;
    

    You should also consider a more meaningful name for it...

Reply
  • It doesn't work like that!

    For a start, if you want a pointer to that structure, why don't you just define it as a pointer to that structure:

    testStructure *ptr;
    

    The type given for a variable in its declation or definition is fixed; if you declare ptr as a pointer to void, then it will always be a pointer to void.
    If you want to use it as a pointer to something else, then you have to cast it at the point that you use it.

    So the cast in your mallo statement is pointless; the cast should come when you reference the pointer:

    ptr = malloc( sizeof(testStructure) );
    

    ((testStructure*)ptr)->a = 5;
    

    You should also consider a more meaningful name for it...

Children