我试图返回一个指向2d char数组的指针(主要是为了练习使用指针,因为我还不太了解它们)。
当我编译它时,我收到消息:
Maze Game.cpp(32): error C2440: 'initializing' : cannot convert from 'char (*)[8]' to 'char **'
第32行是:
char** acBoard = new char[8][8];
以下是源代码:
#include "stdafx.h"
#include <iostream>
char** createGrid();
int main()
{
using namespace std;
char** pBoard = createGrid();
char gameBoard[8][8];
for(int row = 0; row < 8; row++) {
int count = 0;
for(int col = 0; col < 8; col++) {
char temp = **pBoard + count;
gameBoard[row][col] = temp;
cout << gameBoard[row][col];
}
cout << endl;
}
delete pBoard;
pBoard = 0;
return 0;
}
char** createGrid()
{
char** acBoard = new char[8][8];
//Set wall positions
acBoard[1][6] = 'X';
acBoard[1][7] = 'X';
acBoard[3][4] = 'X';
acBoard[3][6] = 'X';
acBoard[3][8] = 'X';
acBoard[4][1] = 'X';
acBoard[4][3] = 'X';
acBoard[4][4] = 'X';
acBoard[4][5] = 'X';
acBoard[4][6] = 'X';
acBoard[4][7] = 'X';
acBoard[5][1] = 'X';
acBoard[5][3] = 'X';
acBoard[5][4] = 'X';
acBoard[5][8] = 'X';
acBoard[6][1] = 'X';
acBoard[6][2] = 'X';
acBoard[6][3] = 'X';
acBoard[6][6] = 'X';
acBoard[6][8] = 'X';
acBoard[7][1] = 'X';
acBoard[7][5] = 'X';
acBoard[7][6] = 'X';
acBoard[7][8] = 'X';
acBoard[8][3] = 'X';
acBoard[8][5] = 'X';
acBoard[8][6] = 'X';
acBoard[8][7] = 'X';
acBoard[8][8] = 'X';
acBoard[1][8] = 'N';
acBoard[7][7] = 'T';
acBoard[5][2] = 'W';
acBoard[2][2] = '$';
return acBoard;
}
任何人都可以向我解释为什么会这样吗?
答案 0 :(得分:1)
它确切地告诉你问题是什么 - char **
和你的2D数组是不兼容的类型。你需要:
char (*acBoard)[8] = new char[8][8];
其他地方相应的变化。或者,您可以更改分配以创建指向其他数组的指针数组。
除此之外:C ++使用0索引数组。
答案 1 :(得分:1)
请参阅link关于使用new分配2D数组的信息。
如果你这样做,理解起来要简单得多:
struct Board
{
char cells[8][8] ;
};
Board* create()
{
Board* board = new Board;
return board;
}
当然,只要我们做到这一点,我们就会意识到这是C ++,将struct
更改为class
并使其成为正确的对象。