[英]How to pass 2D char array to function?
我正在做一個棋盤游戲,在我的主要游戲中有一個2d字符數組供棋盤使用:
char board[*size][*size];
for(int i = 0; i < *size; i++) {
for(int j = 0; j < *size; j++) {
board[i][j] = ".";
}
}
我想在名為playerOneMove(?)的函數中使用此函數,更改其某些元素,然后再次返回main以在playerTwoMove(?)中使用它
我可以用一維整數數組來做到這一點,但我做不到。 我只想學習方法,而不是完整的代碼。
最好的學習方法是看代碼。
以下代碼傳遞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;
}
這只是用於轉換任何種類的2d數組(寬度=高度或寬度!=高度)的數學公式,其中x,y-2d數組的索引; index-一維數組的索引。 這是針對基數1的-第一個2d元素的索引為11(x = 1,y = 1)。 猜猜您可以在任意位置實施它。
2D到1D
索引=寬度*(x-1)+ y
一維到二維
x =(索引/寬度)+ 1
y =((索引-1)%寬度)+ 1
對於基本0-1st元素索引x = 0,y = 0
2D到1D
索引=寬度* x + y
一維到二維
x =索引/寬度
y =(索引-1)%寬度
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.