how to allocate memory for struct itself, and its

2019-08-20 04:57发布

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

4条回答
够拽才男人
2楼-- · 2019-08-20 05:31

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-08-20 05:37

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);
// ...
查看更多
该账号已被封号
4楼-- · 2019-08-20 05:49

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)

查看更多
女痞
5楼-- · 2019-08-20 05:54

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

查看更多
登录 后发表回答