我需要声明一个类型(使用typedef),这是指向2D数组的char指针。

typedef char* board {
    char* arr[8][8];
}chessboard;


但是它不会编译。我也发现了这个:

typedef char board[8][8];


这有效,但实际上不是指向数组的指针。
我将不胜感激,谢谢。

最佳答案

在做

typedef char (*BoardPointer)[8][8]


BoardPointer定义为指向char的8x8数组的类型,因此

BoardPointer boardpointer;


boardpointer定义为指向char的8x8数组的指针。

要分配8x8 char数组,您可以执行以下操作:

BoardPointer boardpointer = malloc(sizeof *boardpointer);
if (NULL == boardpointer)
{
  perror("malloc() failed");
}
else
{
  // use boardpointer here. Set all elements to '\0' for example:
  for (size_t r = 0; r < 8)
  {
    for (size_t c = 0; c < 8)
    {
      (*boardpointer)[r][c] = '\0';
    }
  }

  free(boardpointer);
}




正如其他人指出的那样,typedef ing指针容易出错,并且使代码难以阅读,您可以选择执行以下操作:

typedef char Board[8][8]

Board * boardpointer = malloc(sizeof *boardpointer);
if (NULL == boardpointer)
{
  perror("malloc() failed");
}
else
{
  // use board here. Set all elements to '\0' for example:
  for (size_t r = 0; r < 8)
  {
    for (size_t c = 0; c < 8)
    {
      (*boardpointer)[r][c] = '\0';
    }
  }

  free(boardpointer);
}


要不就

typedef char Board[8][8]

Board board;
// use board here. Set all elements to '\0' for example:
for (size_t r = 0; r < 8)
{
  for (size_t c = 0; c < 8)
  {
    board[r][c] = '\0';
  }
}

关于c - Typedef指向2D数组的指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45894795/

10-11 01:02
查看更多