【问题标题】:Passing a char pointer array to a function in c++将char指针数组传递给C++中的函数
【发布时间】:2014-02-05 03:20:09
【问题描述】:

我正在尝试制作井字游戏,并且我想将井字棋盘位置的二维数组传递给绘制更新棋盘的函数。我希望我的函数“updateBoard”的参数值能够从 main 中获取板的内存地址,这样我就可以在整个程序中使用它而不必担心范围。编译时出现错误:

错误 C2664: 'updateBoard' : 无法将参数 1 从 'char (*)[3][3]' 转换为 'char *[][3]' 1> 指向的类型不相关;转换需要 reinterpret_cast、C-style cast 或 function-style cast

这是我的代码:

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

【问题讨论】:

    标签: c++ arrays pointers char


    【解决方案1】:

    你可以这样做

    #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 的元素。

    【讨论】:

      猜你喜欢
      • 2012-07-28
      • 2021-12-02
      • 2016-03-27
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 2021-09-07
      • 2015-03-17
      相关资源
      最近更新 更多