471,090 Members | 1,644 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,090 software developers and data experts.

dereferencing void pointers by typecasting

Hello everyone,

I am having a problem with typecasting void pointers.I have read the pointer basics but still cant understand why the following test code doesnt work.

void *xyz;

struct abcd
{
int a;
};

struct abcd a,*ptra;
ptra=&a;
xyz=(struct abcd *)ptra; //doesnt work but no error shown.
.
.
printf("%d \n",xyz->a);

}

warning: dereferencing void * pointer (obviously,typecasting didnt work)

error : request for member a in something not a structure or union;

Am i missing some pointer concepts here?


Thanks,
Sritej
Nov 2 '08 #1
3 12194
newb16
687 512MB
Hello everyone,

I am having a problem with typecasting void pointers.I have read the pointer basics but still cant understand why the following test code doesnt work.

void *xyz;

struct abcd
{
int a;
};

struct abcd a,*ptra;
ptra=&a;
xyz=(struct abcd *)ptra; //doesnt work but no error shown.
.
.
printf("%d \n",xyz->a);

}
Information about structure type is not stored in pointer, pointer is just an address.
So when you write xyz->a compiler has no idea on what ->a is and what is its offset within memory block pointed by xyz

Expand|Select|Wrap|Line Numbers
  1. ptra=&a;
  2. xyz=ptra; // no need to typecast here
  3. printf("%d \n",((struct abcd *)xyz)->a);
  4.  
where (struct abcd *)xyz is of type "struct abcd*" and can be used as an argument to ->
Nov 2 '08 #2
thanks a lot for the correction..
so initial declaration of pointer is taken into account while dereferencing so that offsets can be computed .Thats why typecasting is done while dereferencing.

Thanks,
Sritej
Nov 2 '08 #3
AmeL
15
Expand|Select|Wrap|Line Numbers
  1. void *xyz;
  2. struct abcd
  3. {
  4. int a;
  5. };
  6. struct abcd a,*ptra;
  7. ptra=&a;
  8. xyz=(struct abcd *)ptra; //doesnt work but no error shown.
  9. .
  10. .
  11. printf("%d \n",xyz->a);
  12. }
  13.  
Let review your code a bit more!!!
You declared xyz as a pointer to void.
Then after you do like :
xyz = (struct abcd *)ptra; that ptra's type is a pointer to struct abcd.
This instruction means you're trying to typecast from struct abcd pointer to struct abcd pointer ( again ) and trying to assign that to xyz that was declared as pointer to void.

Thanks
/AmeL
Nov 3 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.