如何分配内存结构本身,其成员 [英] how to allocate memory for struct itself, and its members

查看:118
本文介绍了如何分配内存结构本身,其成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的结构:

 结构foo的{
  字符*一个;
  字符* B;
  字符* C;
  字符* D;
};

有可能为结构分配空间本身和它的成员,而不是例如,

 结构美孚F;
F.A =的malloc();
f.b =的malloc();
F.C =的malloc();
F.D =的malloc();
的strcpy(F.A,一个);
的strcpy(f.b,B);
// ..

这样的事情(职高,它并不作品):

 结构美孚F =的malloc(sizeof的(结构F));
strpcy(F.A,一个);
//等等


解决方案

这就是所谓的构造函数。随着处理忽略错误,它可能看起来像:

 结构美孚* new_foo()
{
    结构美孚* OBJ =的malloc(sizeof的(结构富));
    obj->一种= malloc的(...);
    obj-> B =的malloc(...);
    obj-> X =一个new_x(...);
    ...
    返回OBJ;
}

和需要相应的析构函数。如果你发现自己需要经常写code这样的,它可能是时间切换到C ++。)

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

解决方案

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

这篇关于如何分配内存结构本身,其成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆