semantic_c0d3r
semantic_c0d3r

Reputation: 801

Converting void* to struct* and reading struct member values

Here is my code:

typedef struct{
int a;
} DATA;

int main()
{
  DATA *temp, *temp2;
  void *vtemp;
  temp = (DATA *)malloc(sizeof(DATA));
  temp->a = 5;
  vtemp = &temp;
  printf("set value : %d\n", temp->a);  

  // Some ops //

  temp2 = (DATA *)vtemp;
  printf("got value : %d\n", temp2->a);
  return 0;
}

I'm supposed to get "got value" as 5 but i'm getting a random number as follows (probably printing an address?):

set value : 5
got value : 7024656

Upvotes: 0

Views: 72

Answers (2)

Santosh A
Santosh A

Reputation: 5351

Here temp is of type DATA

typedef struct{
    int a;
} DATA;

When vtemp = &temp means vtemp has the address of temp, which is of type DATA* and not DATA. So for you to dereference, you should declare vtemp as void**

change vtemp = &temp; to vtemp = temp; for your program to work or check the below code using void**

int main()
{
  DATA *temp, *temp2;
  void **vtemp;
  temp = (DATA *)malloc(sizeof(DATA));
  temp->a = 5;

  vtemp = (void *)&temp;

  printf("set value : %d\n", temp->a);  

  // Some ops //

  temp2 = *vtemp;
  printf("got value : %d\n", temp2->a);
  return 0;
}

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612844

temp is the address of the struct. When you write:

vtemp = &temp;

you set vtemp to be the address of temp, the variable. So, &temp is actually of type DATA**. When you cast vtemp to be of type DATA*, that is an error. Simple, vtemp is not of type DATA* and your cast does not change that.

I guess that you meant to assign temp to vtemp:

vtemp = temp;

Upvotes: 4

Related Questions