[英]How to pass 2D char array to function?
I am working on a board game and have a 2d char array for board in my main: 我正在做一个棋盘游戏,在我的主要游戏中有一个2d字符数组供棋盘使用:
char board[*size][*size];
for(int i = 0; i < *size; i++) {
for(int j = 0; j < *size; j++) {
board[i][j] = ".";
}
}
I want to use this in my function named playerOneMove(?), change some of its elements and than bring back to main again to use it in playerTwoMove(?) 我想在名为playerOneMove(?)的函数中使用此函数,更改其某些元素,然后再次返回main以在playerTwoMove(?)中使用它
I can do this with 1D integer arrays but i couldn't make this work. 我可以用一维整数数组来做到这一点,但我做不到。 I just want to learn the method, not full code.
我只想学习方法,而不是完整的代码。
The best way to learn is by looking at code. 最好的学习方法是看代码。
The below code passes a 2D array. 以下代码传递2D数组。 Study it.
研究一下。
#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;
}
Here's just math formulas for converting any kind of 2d array (width = height OR width != height) where x, y - indexes of 2d array; 这只是用于转换任何种类的2d数组(宽度=高度或宽度!=高度)的数学公式,其中x,y-2d数组的索引; index - index of 1d array.
index-一维数组的索引。 That's for base 1 - first 2d element has index 11 (x=1, y=1).
这是针对基数1的-第一个2d元素的索引为11(x = 1,y = 1)。 Guess you may implement it wherever you wish.
猜猜您可以在任意位置实施它。
2D to 1D 2D到1D
index = width * (x-1) + y
索引=宽度*(x-1)+ y
1D to 2D 一维到二维
x = (index / width) + 1
x =(索引/宽度)+ 1
y = ((index - 1) % width) + 1
y =((索引-1)%宽度)+ 1
For base 0 - 1st element indexes x=0, y=0 对于基本0-1st元素索引x = 0,y = 0
2D to 1D 2D到1D
index = width * x + y
索引=宽度* x + y
1D to 2D 一维到二维
x = index / width
x =索引/宽度
y = (index - 1) % width
y =(索引-1)%宽度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.