Question

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
Was it helpful?

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++ :).

OTHER TIPS

You can certainly allocate memory for the struct itself and its members in one go, if that's what you're asking. You just have to know how much you're going to need it (in total) and take care of any possible alignmentation issues (not present in this particular case, though).

struct foo *f = malloc(sizeof *f + size_a + size_b + size_c + size_d);
f.a = (char*)(f + 1);
// ...

You can do it if you know all the "dynamic" variable sizes at construction time.

struct foo *f = malloc(sizeof(struct f) + nSizeExtra);

f->a = (char*) (f + 1);
f->b = ((char*) (f + 1)) + nLengthOfA;
f->c = ((char*) (f + 1)) + nLengthOfA + nLengthOfB;
f->d = ((char*) (f + 1)) + nLengthOfA + nLengthOfB + nLengthOfC;

Of course at the end you should free only f (not its members)

Of course you can allocate memory for your struct and it's members, but if you allocate one contiguous memory for the whole thing, you will need to initilize your struct's members anyway, so you can't do what you want as easily as you'd like to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top