在结构中动态分配多个结构
Dynamically Allocating a mulitple Struct within a Struct
我是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;
相关文章:
- C++具有动态分配的字符数组的结构
- 如何为结构字段动态分配字符空间
- 结构内动态分配的数组
- 使用C++动态分配结构的多维数组
- 如何从文件读取到动态分配的指向结构的指针链表中?
- 在 c++ 中将动态分配的数组作为结构成员的分段错误?
- 在读取大型 txt 文件时动态分配结构内的向量
- C++类内部结构动态分配的方法
- 分段错误,在动态分配的结构内动态分配结构
- 动态分配一维结构数组:两种方法
- 在类存储结构中使用动态分配的数组
- 如何在C 中创建动态分配的2D结构阵列
- 动态分配的结构阵列具有动态分配的结构阵列元素
- 结构变量的动态分配
- 我在动态分配结构时遇到问题
- 将C++接口写入动态分配的 C 结构
- 从二进制文件中读取在结构中动态分配的数组
- 为结构动态分配内存
- 从C++中的文件读取时动态分配内存到结构
- 在结构中动态分配多个结构