我想在结构中动态分配结构。我想我能做到这一点。但是当我想用它们执行操作时,我在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);
}
提前谢谢。
答案 0 :(得分:0)
此:
struct bin *binpointer = (struct bin*)calloc(N, sizeof(struct bin));
应该是:
(*myDynamicMembersBinArray).binpointer = calloc(N, sizeof(struct bin));
注意我摆脱了演员表。请参阅this answer了解原因(请记住,在C ++中,您确实需要演员。但它在C中是错误的并且可以隐藏错误。)
答案 1 :(得分:0)
您没有声明myDynamicMembersBinArray
:
struct dynamicbin* myDynamicMembersBinArray = calloc(1, sizeof(struct dynamicbin));
struct bin *binpointer = (struct bin*)calloc(N, sizeof(struct bin));
应该是
(*myDynamicMembersBinArray).binPointer = calloc(N, sizeof(struct bin));
(*myDynamicMembersBinArray
周围的括号很重要)或更好的
myDynamicMembersBinArray->binPointer = calloc(N, sizeof(struct bin));
最后但并非最不重要
printf("%f\n", (*(*myDynamicMembersBinArray).binPointer+i).size);
应该是
printf("%f\n", *((*myDynamicMembersBinArray).binPointer+i).size);
(注意*移到括号之外)或者更好
printf("%f\n", myDynamicMembersBinArray->binPointer[i].size);