In the code, child
is casted to type Parent
, and passed to parentMove
. child
does not have members x
and y
. How does parentMove
access child.parent.x
and child.parent.y
? How does type casting work here? Thx
#include <stdio.h>
typedef struct{
int x, y;
int (*move)();
}Parent;
typedef struct {
Parent parent;
int h, w;
}Child;
int parentMove(Parent* parent, int y, int x){
parent->y+=y;
parent->x+=x;
printf("%d %d", parent->y, parent->x);
return 1;
}
int main(void) {
Parent parent = {.x = 2, .y = 1, .move = &parentMove};
Child child = {.parent = parent, .h = 3, .w = 4};
((Parent*)(&child))->move((Parent*)&child, 10, 10);
return 0;
}