Constructor for structs in C

In C I typically create a function in the style of a constructor which does this. For example (error checking omitted for brevity)

Object* Object_new(int id, int value) { 
  Object* p = malloc(sizeof(Object));
  p->id = id;
  p->value = value;
  return p;
}

...
Object* p1 = Object_new(id++, myValue);

Leave a Comment