在结构中动态分配多个结构

Dynamically Allocating a mulitple Struct within a Struct

本文关键字:结构 动态分配      更新时间:2023-10-16

我是C++新手,需要一些帮助。我有以下代码:

struct Force {
    float X[10];
    float Y[10];
    float Z[10];
};
struct Measurement{
    char serial_number[30];
    struct Force F1;
    struct Force F2;
 };

我应该如何正确分配以下内容?

struct Measurement meas

问题是结构力工作正常;但是,当我尝试定义结构测量测量时,我得到"未处理的异常"错误!

正如我在您的问题中看到的,您正在使用 C,所以这里是 C 的解决方案。

无论您想在哪里拥有结构测量实例,只需键入:

struct Measurement meas;

您将能够访问您的结构元素:

meas.F1.X and so on...

如果您希望进行动态分配(即在运行时),则只需使用 malloc/calloc,如下所示

struct Measurement *meas = (struct Measurement *)malloc(sizeof(struct Measurement));

这样做,您将必须访问您的结构元素,如下所示:

meas->F1.X and so on...

从技术上讲,它的工作方式与您编写的一样,但是结构词在成员上是不必要的(实际上会生成警告,但可以工作。

struct Force {
    float X[10];
    float Y[10];
    float Z[10];
};
struct Measurement {
    char serial_number[30];
    Force F1;
    Force F2;
};

然后在函数中使用如下:

Measurement somevar;
somevar.F1.Y = 999;

现在,执行此操作(并保存堆栈)的正确方法是使用指针。

struct Measurement {
    char serial_number[30];
    Force* F1;
    Force* F2;
};

然后:

Measurement* m = new Measurement;
if (m) {
    m->F1 = new Force;
    m->F2 = new Force;
}

使用后,您必须删除所有指针以避免内存泄漏:

delete m->F1;
delete m->F2;
delete m;

还有另一种方法。用:

struct Force {
    float X[10];
    float Y[10];
    float Z[10];
};
struct Measurement {
    char serial_number[30];
    Force F1;
    Force F2;
};

您可以使用 malloc 分配一定量的内存并将其视为结构(没有时间测试它,但我多次使用这种方法)。

Measurement* m = (Measurement*)malloc(sizeof( size in bytes of both structs ));
// zero memory on m pointer
// after use
free(m);

就这样。

C:

struct Measurement *meas;
meas=(struct Measurement *) malloc(sizeof(Measurement));
              ^                             ^                         
              |                             |                 
              |                             |                
          this is shape                  this is the space allocated

C++:

Measurement *meas;
meas=new Measurement;