将char指针数组传递给c ++中的函数

时间:2014-02-05 03:20:10

标签: c++ arrays pointers char

我正在尝试制作一个tic tac toe游戏,我想将我的2d数组tic tac toe board位置传递给我绘制更新板的功能。我希望我的函数“updateBoard”的参数值能够从main接收板的内存地址,所以我可以在整个程序中使用它而不用担心范围。当我编译它时,我收到错误:

  

错误C2664:'updateBoard':无法将参数1从'char(*)[3] [3]'转换为'char * [] [3]'1>指向的类型是无关的;转换需要reinterpret_cast,C风格的转换或函数式转换

继承我的代码:

#include "stdafx.h"
#include <iostream>

using namespace std;

void updateBoard (char *n[3][3])
{

}
int getMove ()
{
int input;
cout <<"\n";
cout <<"1 for square 1| 2 for square 2| and so on...  : ";
cin >>input;

return 0;
}

int main ()
{
const int WIDTH = 3;
const int HEIGHT = 3;
char board [WIDTH][HEIGHT] = {' ', ' ', ' ',
                              ' ', ' ', ' ',
                              ' ', ' ', ' '};
updateBoard(&board);
char f;
cin >>f;
}

1 个答案:

答案 0 :(得分:2)

您可以采取以下方式

#include "stdafx.h"
#include <iostream>

using namespace std;

const int WIDTH = 3;
const int HEIGHT = 3;

typedef char TBoard [WIDTH][HEIGHT];

void updateBoard ( TBoard board, int width )
{

}

int main ()
{
TBoard board = {' ', ' ', ' ',
                ' ', ' ', ' ',
                ' ', ' ', ' '};
updateBoard( board, WIDTH);
char f;
cin >>f;
}

至于你的错误,那么函数参数应定义为

void updateBoard (char ( *n )[3][3])
{

}

char ( *n )[3][3]表示指向

的二维数组的指针

char * n[3][3]表示指针的二维数组char *

在函数内部你应该写

( *n )[i][j]

访问索引为i和j的元素。

相关问题