简体   繁体   中英

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:

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(?)

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. 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; index - index of 1d array. That's for base 1 - first 2d element has index 11 (x=1, y=1). Guess you may implement it wherever you wish.

2D to 1D

index = width * (x-1) + y

1D to 2D

x = (index / width) + 1

y = ((index - 1) % width) + 1

For base 0 - 1st element indexes x=0, y=0

2D to 1D

index = width * x + y

1D to 2D

x = index / width

y = (index - 1) % width

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM