[英]Passing a char pointer array to a function in c++
我正在嘗試制作一個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;
}
您可以通過以下方式進行操作
#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的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.