c - Where is this pointer actually pointing? -
c - Where is this pointer actually pointing? -
i'm trying larn c using learncodethehardway c book. in ex19 have next code:
int monster_init(void *self) { monster *monster = self; monster->hit_points = 10; homecoming 1; } int monster_attack(void *self, int damage) { monster *monster = self; printf("you attack %s!\n", monster->proto.description); monster->hit_points -= damage; if(monster->hit_points > 0) { printf("it still alive.\n"); homecoming 0; } else { printf("it dead.\n"); homecoming 1; } } object monsterproto = { .init = monster_init, .attack = monster_attack }; this object structure:
typedef struct { char *description; int (*init)(void *self); void (*describe)(void *self); void (*destroy)(void *self); void *(*move)(void *self, direction direction); int (*attack)(void *self, int damage); } object; and monster structure:
struct monster { object proto; int hit_points; }; i'm having tough time wrapping head around monster_init , monster_attack functions. have monsterproto variable of type object defined , within there .init set monster_initfunction , .attack set monster_attack function.
i think understand notion of void in terms of declaring function has side effects doesn't need homecoming something. don't understand void *self pointer pointing @ , why allow me phone call function no arguments? purpose of self pointer?
i didn't want include much code here if not plenty context reply question, can find code here.
i appreciate pointers in right direction; nu pun intended :)
this code seems implementing kind of object-oriented approach.
self address of struct monster pass functions. each of functions operates on individual object, , passing in pointer object how know 1 work on.
this:
.init = monster_init, is not "calling function no arguments" - init fellow member of struct pointer function returning int , accepting single void * parameter, , line assigns address of monster_init() it. way, if have pointer object, can phone call int n = myobject->proto.init(&myobject); or similar without knowing actual function gets called. different object, might calling different function same line of code.
c pointers
Comments
Post a Comment