Created
June 17, 2020 07:02
-
-
Save igormorgado/eb0e748a0aab831fa005b50f9b273552 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <glib.h> | |
#include <gmodule.h> | |
struct entity { | |
int32_t value; // 4 bytes | |
char name[12]; // 12 bytes | |
}; | |
struct manager { | |
char name[256]; | |
GArray *entities; | |
}; | |
void manager_entity_add (struct manager *manager, struct entity entity); | |
void | |
manager_entity_add (struct manager *self, struct entity entity) | |
{ | |
g_array_append_val(self->entities, entity); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
struct manager *mgr = malloc(sizeof *mgr); | |
g_strlcpy(mgr->name, "MANAGER", 256); | |
mgr->entities = g_array_sized_new(TRUE, TRUE, sizeof(struct entity), 512); | |
// Method 1: Anonymous struct | |
manager_entity_add(mgr, (struct entity){ .name = "name1", .value = 42}); | |
// Method 2: Stack struct | |
struct entity t2; | |
g_strlcpy(t2.name, "name2", sizeof(t2.name)); | |
t2.value = 23; | |
manager_entity_add(mgr, t2); | |
// Method 3: Heap struct | |
struct entity *t3 = malloc(sizeof *t3); | |
g_strlcpy(t3->name, "name3", sizeof(t3->name)); | |
t3->value = 1; | |
manager_entity_add(mgr, *t3); | |
// Print entities | |
g_print("# entities: %d\n", mgr->entities->len); | |
struct entity *t; | |
for(size_t i=0; i< mgr->entities->len; i++) | |
{ | |
t = &g_array_index((mgr->entities), struct entity, i); | |
g_print("Object %s @ %p\n", t->name, (void*)&(*t)); | |
} | |
free(t3); | |
g_array_free(mgr->entities, TRUE); | |
free(mgr); | |
return EXIT_SUCCESS; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment