如何在C中初始化3d数组 - 指针数组数组

时间:2015-05-05 19:39:17

标签: c arrays pointers malloc

我正在编写一个游戏,可以生成下一个可能的动作。我需要生成下一步动作才能执行搜索。但是我不知道如何在C中做到这一点。

生成电路板的代码是:

#include <stdio.h> //prints 
#include <stdbool.h> //bool
#include <stdlib.h>  //malloc 

static const int BOARD_SIZE = 6;
typedef int **BOARD;

void print_board(BOARD b){
    int i,j;
    printf("BOARD array is:\n");
    for (i=0; i<BOARD_SIZE; i++) {
        for (j=0; j<BOARD_SIZE; j++){
            printf("%d ",b[i][j]);
        }
        printf("\n");
    }
}

BOARD set_game(){
//set board
//all the squares starts with 2 
    int i, j;

    BOARD b = malloc(sizeof(int *) * BOARD_SIZE);
    for (i = 0; i < BOARD_SIZE; i++){
        b[i] = malloc(sizeof(int) * BOARD_SIZE);
    }

    for (i=0; i<BOARD_SIZE; i++) {
        for (j=0; j<BOARD_SIZE; j++){
            //position player 0 peons
            if(j == 0){
                b[i][j] = 0;
            }
            //position player 1 peons
            else if(j == BOARD_SIZE-1){
                b[i][j] = 1;
            }else{
                b[i][j] = 2;
            }
        }
    }

    print_board(b);
    return b;
}

// Game
int main(){
// a pointer to an int.
    BOARD p, board;
    p = set_game();

    board = board_status(p);
    return 0;

}

打印:

BOARD array is:
0 2 2 2 2 1 
0 2 2 2 2 1 
0 2 2 2 2 1 
0 2 2 2 2 1 
0 2 2 2 2 1 
0 2 2 2 2 1

我现在需要制作一个数组数组,以生成所有下一个可能的板,例如,当玩家0从b [0] [0]移动到b [0] [1]时,这是一片叶子的分支。

BOARD array is:
2 0 2 2 2 1
0 2 2 2 2 1 
0 2 2 2 2 1 
0 2 2 2 2 1 
0 2 2 2 2 1 
0 2 2 2 2 1

我该如何分配这个数组? 我需要一个包含所有其他board_status的分支数组,之后我将执行搜索。 我不确定数组的类型,如何声明它?这将是一个BOARD阵列?

我尝试使用这种方法,我发现here但似乎有些不对劲。它给了我一个错误:

  从类型'int'数组[i] = b [i] [j];

分配类型'branches'时

不兼容的类型

//generate ALL possible moves
void generatePossibleMoves(int player){
int i, j;
typedef struct
{
    int BOARD[BOARD_SIZE];
} branches;

branches** array = NULL;

void InitBranches( int num_elements )
{
    array = malloc( sizeof( branches ) * num_elements);

    if( !array )
    {
       printf( "error\n" );
       exit( -1 );
    }

    for(i = 0; i < num_elements; i++ )
    {
        for(j = 0; j < BOARD_SIZE; j++ )
        {
           BOARD b = set_game();
           array[i] = b[i][j];
           printf("%d", array[i]);
        }
        printf("\n");
    }
}

InitBranches(4);


}

有人可以帮帮我吗?谢谢。

1 个答案:

答案 0 :(得分:2)

你不应该在函数中使用函数,将generatePossibleMoves移出typedef structarray也应该在函数之外。

您对malloc*的声明不符合,您应该删除声明中的sizeof或在BOARD* InitBranches( int num_elements ) { int i; BOARD* array = malloc(num_elements * sizeof *array); if( !array ) { printf( "error\n" ); exit( -1 ); } for(i = 0; i < num_elements; i++ ) { array[i] = set_game(); } return array; } void generatePossibleMoves(int player){ BOARD* array = InitBranches(4); //do your moves here } 中添加一个。{/ p>

猜猜你想做什么:

array[0]

这将创建您的主板array[3]的4个分支,直到os = system_dependent('getos')