468,768 Members | 1,318 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,768 developers. It's quick & easy.

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 11667
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.

Similar topics

5 posts views Thread by Vivek | last post: by
4 posts views Thread by Pushkar Pradhan | last post: by
3 posts views Thread by sam | last post: by
5 posts views Thread by Rahul | last post: by
18 posts views Thread by bcpkh | last post: by
160 posts views Thread by raphfrk | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by Marin | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.