I'm trying to create an array that can be resized, and automatically renumbered, at the moment, what I have works for up to a 3x3 array, but anything larger than that doesn't work. I've tried doing this with int instead of char for the type or the array, but then I'm not able to write a character to the board, only the ascii numerical equivalent.
Any help would be appreciated, thanks.

Board.cpp

void Board::create()
{
    ptr = new char *[width];

    for (int i=0;i<width;i++)
    {
        *(ptr + i) = new char[height];
    }

    int k = 1;
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j<height;j++)
        {
            *(*(ptr+i)+j) = k++;
        }
    }
}

The pointer refers to the protected char **ptr

Board.h

class Board
{
    public:
    void create();
    void display();
    void end();
    void set_height(int);
    void set_width(int);
    void write();

    protected:
    int height, width;
    char **ptr;
    char Player;
};

Recommended Answers

All 4 Replies

ptr = new char *[width];

 for (int i = 0; i < width; i++)
 {
     ptr[i] = new char[height];
 }

Code for a 2 dimensional array of char that could be sized to any width and height would stop there. The rest of what you have looks like you would use if you were trying for a 3 dimensional (cube, box, whatever instead of board) array. That is, if you could retain your sanity with all the detractions of the dereferences and pointer math.

Another common option is to leave the board in a single dimensional array. Depending on how you interface to the board, it has advantages and disadvantages.

For example, a 3 x 3 board would use 9 elements in an array. The first 3 would be the first row (or first column depending on your preference) the next 3 would be the second row and the last 3 would be the third and final row.

// ptr is just a char * in my class
void Board::create()
{
    ptr = new char [ width * height ];

    // filling the cells with numbers (I don't know why)
    int k = 1;
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j<height;j++)
        {
            ptr[i * width + j] = k++;
        }
    }
}

For more help with the int vs char for the array implementation, it would help to have a better idea of how the board will be used.

Nah, that worked, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.