Home > front end >  accessing a struct variable from a void pointer from a node pointer
accessing a struct variable from a void pointer from a node pointer

Time:10-15

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

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;
}

CodePudding user response:

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.

  • Related