【问题标题】:How to pass 2D char array to function?如何将二维字符数组传递给函数?
【发布时间】:2018-03-12 12:37:27
【问题描述】:

我正在开发一款棋盘游戏,我的主游戏中有一个 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(?) 中使用它

我可以用一维整数数组来做到这一点,但我无法做到这一点。我只是想学习方法,而不是完整的代码。

【问题讨论】:

  • My preferred method。请注意,您还可以创建一个模板函数来执行此操作。模板不必像我的示例中那样是传递函数;它可以是一个完整的函数,可以为您传递的每个数组 T,N,M 实例化。
  • 这个explanation对我学习二维数组很有帮助。
  • 这并没有解决问题,但我很难想象为什么size 会是指针而不是main 中的值。

标签: c++ arrays


【解决方案1】:

最好的学习方法是查看代码。

下面的代码传递一个二维数组。研究一下。

#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;
}

【讨论】:

  • 这段代码不只是展示了如何从函数返回一个数组吗?我的数组已声明并填充为 main ,我想在函数中使用和更改它的元素,然后返回它。
  • 好的。我明白。但是您可以轻松地将函数中的内容移到主函数中。
【解决方案2】:

这只是用于转换任何类型的二维数组(宽度 = 高度或宽度!= 高度)的数学公式,其中 x,y - 二维数组的索引; index - 一维数组的索引。 这适用于基数 1 - 第一个 2d 元素的索引为 11(x=1,y=1)。 猜猜你可以在任何你想要的地方实现它。

二维到一维

索引 = 宽度 * (x-1) + y

一维到二维

x = (索引/宽度) + 1

y = ((index - 1) % 宽度) + 1

对于基数 0 - 第一个元素索引 x=0, y=0

二维到一维

索引 = 宽度 * x + y

一维到二维

x = 索引/宽度

y = (index - 1) % 宽度

【讨论】:

    猜你喜欢
    • 2015-05-27
    • 1970-01-01
    • 2021-05-27
    • 2023-03-06
    • 1970-01-01
    • 2020-11-01
    相关资源
    最近更新 更多