I’m adding a programming section containing algorithms and other programming related topics.
I’m adding a programming section containing algorithms and other programming related topics.
I was playing around with c and creating pseudo type objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | #include <stdio.h> #include <string.h> #include <stdlib.h> #define NAMESIZ 32 /*size of name array */ typedef struct object { char name[NAMESIZ]; int number; void (*print)(struct object*); /*function pointer declarations*/ int (*getNumber)(struct object*); } Object; void object_print(Object* this) /* functions which do operations on the Object structure */ { printf("%s\n", this->name); } int object_getNumber(Object *this) { return this->number; } Object * object_create(char* name, int number) /*creates a new Object and returns a Object pointer*/ { Object * obj = NULL; if((obj = malloc(sizeof(Object))) != NULL) { strncpy(obj->name, name, NAMESIZ); obj->print = &object_print; /*set function pointer for print*/ obj->getNumber = &object_getNumber; /*set function pointer for getNumber*/ obj->number = number; } return obj; } void object_delete(Object ** obj) /*free a Object from memory and sets the Object pointer to NULL*/ { free(*obj); *obj = NULL; } int main() { Object * obj = NULL; if((obj = object_create("My Name", 70)) != NULL) { (*obj->print)(obj); /*call void function print. Also we could make a operation on the object by object_print(obj); */ printf("%d\n", (*obj->getNumber)(obj)); /*call int getNumber function*/ object_delete(&obj); } #ifdef WIN32 system("pause"); #endif return 0; } |