【发布时间】:2015-07-23 20:40:00
【问题描述】:
我想在结构中动态分配结构。我想我可以做到这一点。但是,当我想对它们执行操作时,在 Visual C++ 下会出现访问冲突错误。也许初始化有问题。顺便说一句,我怎样才能初始化动态分配的myDynamicMembersBinArray?我尝试了以下方法:
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* ========== Define structures ========== */
/* Create just the identifier */
struct bin{
char *tag;
float size;
};
/* Declare another structure which will hold the bin structure */
struct dynamicbin{
struct bin *binPointer;
};
/* I use calloc so that zero-filling is done */
myDynamicMembersBinArray = (struct dynamicbin*)calloc(1, sizeof(struct dynamicbin));
struct bin *binpointer = (struct bin*)calloc(N, sizeof(struct bin));
/* This one fails */
for (int i=0; i<N; i++){
printf("%f\n", (*(*myDynamicMembersBinArray).binPointer+i).size);
}
提前谢谢你。
【问题讨论】:
-
不要转换
malloc()& al的结果。实际上不要将 void * 转换为任何其他指针类型。此外,`malloc()` & co 可能返回 NULL。 总是检查这个。 -
感谢您的建议。首先,我只是想让分配工作。