Here is my (probably primitive) way of imitating classes and object creation/destruction in C.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> //------------------------------------------------------------------------------------------------------------- // Use a struct to function as the data part of the class. struct Astruct { int N[10]; bool B; }; // Make a function to return a new instance of the struct. struct Astruct* newAstruct(void) { return malloc(sizeof(struct Astruct)); } // Make functions which take the struct as a parameter. void AstructSetN(struct Astruct* as, int index, int value) { as->N[index] = value; } int AstructGetN(struct Astruct* as, int index) { return as->N[index]; } void AstructSetB(struct Astruct* as, bool value) { as->B = value; } bool AstructGetB(struct Astruct* as) { return as->B; } //------------------------------------------------------------------------------------------------------------- int main(int argc, char *argv[]) { struct Astruct* A; int Nval; bool Bval; char c; A = newAstruct(); AstructSetN(A, 4, 6); AstructSetB(A, true); Nval = AstructGetN(A, 4); Bval = AstructGetB(A); printf("Nval = %u\n", Nval); printf("Bval = %u\n\n", Bval); free(A); struct Astruct* C; C = newAstruct(); AstructSetN(C, 7, 3); AstructSetB(C, false); Nval = AstructGetN(C, 7); Bval = AstructGetB(C); printf("Nval = %u\n", Nval); printf("Bval = %u\n\n", Bval); c = getchar(); return 0; }
Bookmarks