我需要创建一个图形并在其节点中存储几个变量。为此我想到了创建一个带有数组和整数的结构。然后创建一个2-d数组,它将保存我创建的所有节点,第二个数组用于保存节点之间的连接。我的问题是,当我尝试初始化我的节点数组时,程序停止工作。有人能告诉我我做错了什么吗?
struct node {
int KEYS_UNLOCKED[43];
int points_given;
};
struct node **NODE_MAT;
NODE_MAT = malloc(doors*sizeof(struct node *) * sizeof(struct node));
for(i=0; i<doors; i++)
NODE_MAT = malloc(doors*sizeof(struct node *) * sizeof(struct node));
for(i=0; i<doors; i++)
{
for(j=0; j<doors; j++)
{
for (k=0; k<43; k++)
NODE_MAT[i][j].KEYS_UNLOCKED[k] = 0;
NODE_MAT[i][j].points_given = 0;
}
}
答案 0 :(得分:1)
typedef struct
{
int KEYS_UNLOCKED[43];
int points_given;
}node ;
node **NODE_MAT;
NODE_MAT = (node **)malloc(doors*sizeof(node *));
for(i=0; i<doors; i++)
NODE_MAT[i] = (node *)malloc(doors*sizeof(node));
for(i=0; i<doors; i++)
{
for(j=0; j<doors; j++)
{
for (k=0; k<43; k++)
NODE_MAT[i][j].KEYS_UNLOCKED[k] = 0;
NODE_MAT[i][j].points_given = 0;
}
}
// At end don't forget to free memory !
for(i = 0; i < doors; i++)
free(NODE_MAT[i]);
free(NODE_MAT);
答案 1 :(得分:0)
typedef struct node
{
int KEYS_UNLOCKED[43];
int points_given;
};
struct node **NODE_MAT;
NODE_MAT = malloc(doors*doors*sizeof(struct node *));
for(i=0; i<doors*doors; i++)
NODE_MAT[i] = malloc(sizeof(struct node));
for(i=0; i<doors; i++)
{
for(j=0; j<doors; j++)
{
for (k=0; k<43; k++)
NODE_MAT[i*doors+j]->KEYS_UNLOCKED[k] = 0;
NODE_MAT[i*doors+j]->points_given = 0;
}
}