C++/pointer casting
Expert: Joydeep Bhattacharya - 3/30/2008
QuestionHi Joydeep,
I am sturggling with a peace of code mainly its about casting a pointer to one type of structure to a pointer to another type of structure.
the confusion begins with the following line...(modified to highlight the actual prob)
#define TEST_MACRO(con) ((struct second *) &first[1])
/*here it would return a pointer to second, but the question is why it uses [1]
Here in this example "first" and "second" are two different structures*/
Then later in the code:
void somefucntion (struct first * fptr)
{
struct second * sptr= TEST_MACRO(fptr);
/*then they use sptr to access various fields in the second structure e.g */
a_pointer= sptr->first_element;
.
.
.
.
Now my question is that after typecasting a pointer of one type of structure to another one, how can we use that (in this case the sptr) to access its members, i mean how values are assigned to them just by typecasting one pointer to another and in this case they are completly different structures. Thanks in advance!
Regards,
Khan
AnswerHi Khan
When two structures are different this is not a safe practice to typecast it like that. What happens internally is it takes up data bytes after bytes and keeps dumping it into the other structure variable, so this never assures that the structure variable(second) will be initialized properly.
Please lemme know if you have any more doubts.
regards
Joydeep Bhattacharya
http://www.scodz.com