0

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
semantic_c0d3r
  • 819
  • 2
  • 15
  • 31

2 Answers2

4

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;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

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;
}
Santosh A
  • 5,173
  • 27
  • 37