Typedef指向2D数组的指针

时间:2017-08-26 11:22:58

标签: c multidimensional-array typedef

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

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

但它不会编译。我也找到了这个:

typedef char board[8][8];

这可行,但它实际上并不是指向数组的指针。 我很感激任何想法,谢谢。

1 个答案:

答案 0 :(得分:3)

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指针容易出错并且使代码难以阅读,您也可以这样做:

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