我正在制作一个棋盘游戏并且在我的主要游戏中有一个2d char数组:
char board[*size][*size];
for(int i = 0; i < *size; i++) {
for(int j = 0; j < *size; j++) {
board[i][j] = ".";
}
}
我想在我的名为playerOneMove(?)的函数中使用它,更改它的一些元素,然后再次返回main以在playerTwoMove中使用它(?)
我可以使用1D整数数组执行此操作,但我无法使其工作。我只是想学习这个方法,而不是完整的代码。
答案 0 :(得分:0)
最好的学习方法是查看代码。
以下代码传递2D数组。研究它。
#include <iostream>
#include <cstdio>
using namespace std;
// Returns a pointer to a newly created 2d array the array2D has size [height x width]
int** create2DArray(unsigned height, unsigned width){
int** array2D = 0;
array2D = new int*[height];
for (int h = 0; h < height; h++){
array2D[h] = new int[width];
for (int w = 0; w < width; w++){
// fill in some initial values
// (filling in zeros would be more logic, but this is just for the example)
array2D[h][w] = w + width * h;
}
}
return array2D;
}
int main(){
printf("Creating a 2D array2D\n");
printf("\n");
int height = 15;
int width = 10;
int** my2DArray = create2DArray(height, width);
printf("Array sized [%i,%i] created.\n\n", height, width);
// print contents of the array2D
printf("Array contents: \n");
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++)
{
printf("%i,", my2DArray[h][w]);
}
printf("\n");
}
// important: clean up memory
printf("\n");
printf("Cleaning up memory...\n");
for ( h = 0; h < height; h++){
delete [] my2DArray[h];
}
delete [] my2DArray;
my2DArray = 0;
printf("Ready.\n");
return 0;
}
答案 1 :(得分:0)
这里只是用于转换任何类型的2d数组(宽度=高度或宽度!=高度)的数学公式,其中x,y - 2d数组的索引; index - 1d数组的索引。 对于基数1 - 第一个2d元素的那个具有索引11(x = 1,y = 1)。 猜猜你可以随意实现它。
2D到1D
index = width *(x-1)+ y
1D到2D
x =(索引/宽度)+ 1
y =((index - 1)%width)+ 1
对于基数0 - 第一个元素索引x = 0,y = 0
2D到1D
index = width * x + y
1D到2D
x =索引/宽度
y =(index - 1)%width