/* Compilation: gcc -std=c99 -Wall -Wextra --pedantic -g -Wstrict-prototypes -Wmissing-prototypes vec_main.c vec.c */ #include #include "vec.h" int main(int argc __attribute__((unused)), char*argv[] __attribute__((unused))) { /* The equivalent of a constructor call */ struct vector* v = vector_create(5); for (int i = 0; i < 5; ++i) { /* The equivalent of calling v.push_back We indicate the * membership by naming convention, prepending vector_ to the * function, and by taking the equivalent of 'this' as first * parameter */ vector_push_back(v, i); } for (int i = 0; i < 5; ++i) { printf("%d\n", vector_at(v, i)); } /* The equivalent of a destructor, we need to call it manually! */ vector_delete(v); } #if 0 /* Sometimes you really want to avoid using dynamic memory (malloc, * free) as it puts a heavy burden on you to manage the memory. * * If your struct are fully defined in the header file you can. * * This is seen in Pintos in for example threads/synch.h */ struct array { int used_size; int max_size; int data[128]; }; int main(int argc, char*argv[]) { /* Create array object as a local variable. It must be a full object * to get memory for it, a pointer will not suffice. */ struct array a; /* Pass adress of object to get it initialized */ array_init(&a); for (int i = 0; i < 5; ++i) { array_push_back(&a, i); } for (int i = 0; i < 5; ++i) { printf("%d\n", array_at(&a, i)); } /* Call cleanup function (destructor) if one is defined */ array_clenup(&a); } #endif