我需要声明一个类型(带有typedef),这是指向2D数组的char指针。
typedef char* board {
char* arr[8][8];
}chessboard;
但它不会编译。我也找到了这个:
typedef char board[8][8];
这可行,但它实际上并不是指向数组的指针。 我很感激任何想法,谢谢。
答案 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';
}
}