You are here:

C++/pointer casting

Advertisement


Question
Hi 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


Answer
Hi 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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joydeep Bhattacharya

Expertise

TSR, Socket and Very Complex Mathematical Problem

Experience

Worked on many OOP projects with design patterns

Organizations
http://www.scodz.com

Publications
http://www.scodz.com

Education/Credentials
Master of Computer Applications

Awards and Honors
Being a proud owner of a website of programming called http://www.scodz.com

Past/Present Clients
http://www.funforu.com http://www.dhoondho.com http://analysingc.50webs.com

©2016 About.com. All rights reserved.