Chris Randall
Chris Randall

Reputation: 25

Trying to return a point to a 2d char array

I'm trying to return a pointer to a 2d char array (mainly just for practice using pointers since I don't understand them too well yet).

When I compile this I get the message:

Maze Game.cpp(32): error C2440: 'initializing' : cannot convert from 'char (*)[8]' to 'char **'

Line 32 is:

char** acBoard = new char[8][8];

Here is the source code:

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

}

Can anyone explain to me why this is happening?

Upvotes: 0

Views: 153

Answers (2)

Carl Norum
Carl Norum

Reputation: 225112

It's telling you exactly what the problem is - char ** and your 2D array aren't compatible types. You need:

char (*acBoard)[8] = new char[8][8];

And corresponding changes elsewhere. Alternately, you could change your allocation to create an array of pointers to other arrays.

Aside: C++ uses 0-indexed arrays.

Upvotes: 1

Keith
Keith

Reputation: 6834

See link regards allocating a 2D array using new.

It's much simpler to understand if you do this:

struct Board
{
    char cells[8][8] ;
};

Board* create()
{
    Board* board = new Board;
    return board;
}

And of course as soon as we get that far, we realise this is C++, change struct to class and make it a proper object.

Upvotes: 1

Related Questions