Search code examples
cstructdynamic-allocation

how to allocate memory for struct itself, and its members


I have this struct:

struct foo {
  char *a;
  char *b;
  char *c;
  char *d;
};

it's possible allocate space for struct itself and its members instead of e.g,

struct foo f;
f.a = malloc();
f.b = malloc();
f.c = malloc();
f.d = malloc();
strcpy(f.a, "a");
strcpy(f.b, "b");
//..

something like this(of couse that it doesn't works):

struct foo f = malloc(sizeof(struct f));
strpcy(f.a, "a");
//etc

Solution

  • This is called a constructor. With error handling omitted, it may look like:

    struct foo *new_foo()
    {
        struct foo *obj = malloc(sizeof(struct foo));
        obj->a = malloc(...);
        obj->b = malloc(...);
        obj->x = new_x(...);
        ...
        return obj;
    }
    

    and need a corresponding destructor. If you find yourself needing to write code like this often, it may be time to switch to C++ :).