无法在结构中创建模拟的2D动态数组

时间:2014-06-22 10:49:36

标签: c pointers

struct Level_Info
{
  char **Map;
} Level[Level_Amount];

for (int Cnt_1 = 0; Cnt_1 < Level_Amount; Cnt_1++)
{
  Level[Cnt_1].Map = malloc(Rbn_Col * sizeof(char*));
  for (int Cnt_2 = 0; Cnt_2 < Rbn_Col; Cnt_2++)
    Level[Cnt_1].*(Map+Cnt_2) = malloc(Rbn_Row * sizeof(char)); /* line 10 */
}

GCC在第10行说expected identifier before 「*」 token,那么如何解决?

1 个答案:

答案 0 :(得分:4)

替换

Level[Cnt_1].*(Map+Cnt_2) = malloc(Rbn_Row * sizeof(char));

*(Level[Cnt_1].Map+Cnt_2) = malloc(Rbn_Row * sizeof(char));

或只是

Level[Cnt_1].Map[Cnt_2] = malloc(Rbn_Row * sizeof(char));

由于定义sizeof(char)总是1,你也可以

Level[Cnt_1].Map[Cnt_2] = malloc(Rbn_Row);

或保持Map要做的事情的灵活性

Level[Cnt_1].Map[Cnt_2] = malloc(Rbn_Row * sizeof(Level[Cnt_1].Map[Cnt_2][0]));

另外请注意索引数组的首选类型是size_t,而不是int

所以你的代码片应该是这样的:

struct Level_Info
{
  char ** Map;
} Level[Level_Amount];

for (size_t Cnt_1 = 0; Cnt_1 < Level_Amount; ++Cnt_1)
{
  Level[Cnt_1].Map = malloc(Rbn_Col * sizeof(Level[Cnt_1].Map[0]));

  for (size_t Cnt_2 = 0; Cnt_2 < Rbn_Col; ++Cnt_2)
  {
    Level[Cnt_1].Map[Cnt_2] = malloc(Rbn_Row * sizeof(Level[Cnt_1].Map[Cnt_2][0]));
  }
}