You are here:

C++/pointer casting


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!


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.

Joydeep Bhattacharya


All Answers

Answers by Expert:

Ask Experts


Joydeep Bhattacharya


TSR, Socket and Very Complex Mathematical Problem


Worked on many OOP projects with design patterns



Master of Computer Applications

Awards and Honors
Being a proud owner of a website of programming called

Past/Present Clients

©2017 All rights reserved.

[an error occurred while processing this directive]