Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

accessing a struct variable from a void pointer from a node pointer

I am very new to C (am trying to code in C89 specifically), and I’m trying to better understand how void pointers and structs work.
I was messing around and was able to access a variable inside a struct from just a plain void pointer variable. But when I put that void pointer variable inside a struct, I get an error.

The only similar problems I’ve found online are people accessing a struct from a void pointer, but not a from a void pointer that is inside of a struct itself.

When I run this code, I get an error;
"error: expected identifier before ‘(‘ token"
image of error message

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help would be very much appreciated!

struct box
{
    int val;
};

struct Node
{
     void * data;
};

int main()
{
struct Node * node;
node = (struct Node *)malloc(sizeof(struct Node));

node->data = (struct box *)malloc(sizeof(struct box));

(*node).(*(struct box *)data).val = 5;

printf("val:   %d \n", (*node).(*(struct box *)data).val);

free(node->data);
free(node;)

return 0;
}

>Solution :

The right operand of the . operator cannot be some general expression. It must be a member name of the union or structure being accessed.

After (*node)., you can write data to access the value of the data member. Then (*node).data is an expression you can operate on further. You can convert that expression to struct box * and dereference it with * (struct box *) (*node).data, and then you can access the val member of that structure with (* (struct box *) (*node).data).val.

And of course the -> operator allows you to replace combinations of * and . with the simpler ->, giving ((struct box *) node->data)->val.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading