Question

I have a basic typecasting question... I have a struct

typedef struct teststruct {
  int a;
} test;

And a simple function

void testfunc(void **s)
{
  printf("trying malloc\n");
  s[0] = (test*)s[0];
  s[0] = (test*)malloc(sizeof(test));
  s[0]->a = 2;
}

However when I compile, I get

test.c:21:7: error: member reference base type 'void' is not a structure or union
  s[0]->a = 2;

What am I doing wrong?

Thanks much for all your help :) Vik.

Was it helpful?

Solution

This line is meaningless:

 s[0] = (test*)s[0];

As it assigns s[0] to itself.

I suspect that you think it changes the type of s[0] from a void* to a test*.
But that is not accurate.

Type-casts only affect how a variable is interpreted immediately, at the point of the type-cast.
It does not change the type of the variable in any lasting sense.

As a result, when your program reaches this line:

s[0]->a = 2;

s[0] is still a void*, and so de-referencing it for variable a is not valid.

What you really want is:

((test*)s[0])->a = 2;

OTHER TIPS

That is because you can not change the type of a variable wuthin your scope. You have to define a new one with the new type.

void testfunc(void **s)
{
  printf("trying malloc\n");
  test * s_test_type = s[0]; // no need to cast to/from void *
  s_test_type = (test*)s[0];
  s_test_type = (test*)malloc(sizeof(test));
  s_test_type->a = 2;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top