how to allocate memory for struct itself, and its members

蓝咒 提交于 2019-12-13 06:06:10

问题


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

回答1:


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




回答2:


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);
// ...



回答3:


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)




回答4:


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.



来源:https://stackoverflow.com/questions/12237074/how-to-allocate-memory-for-struct-itself-and-its-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!