-2

我需要创建一个图形并在其节点中存储几个变量。为此,我想创建一个带有数组和整数的结构。然后创建一个二维数组,该数组将保存我创建的所有节点,第二个数组用于保存节点之间的连接。我的问题是,当我尝试初始化节点数组时,程序停止工作。有人可以告诉我我做错了什么吗?

 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;
        }
    }
4

2 回答 2

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);
于 2013-08-17T12:51:37.790 回答
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;
  }
}
于 2013-08-17T12:59:24.573 回答