Issues with an infinite loop when setting up a two dimenstial array of pointers

0

Im trying to setup a two dimensional array of pointers but, i'm having issues actually allocating the memory. Whenever I try to write values to the array im getting access writing location error.

Grid.h

class Grid 
{
public:
    Grid();

private:
    int x;
    int y;
    int row;
    int col;
    Grid*** array2D;
    
};

Grid.cpp

Grid::Grid()
{
    row = 32;
    col = 30;

     // Allocate memory to point to.
    array2D = new Grid**[row];
    for (int i = 0; i < row; i++) {
        array2D[i] = new Grid*[col];
        }


    for (int i = 0; i <= row; i++)
    {
        for (int j = 0; j <= col; j++)
        {
            array2D[i][j]->x=6;
            array2D[i][j]->y =5;
            
        }
    }
Unhandled exception at 0x000C1CC8 in Project.exe: 0xC0000005: Access violation writing location 0xCDCDCE29.

Exception thrown at 0x000C1CC8 in Project.exe: 0xC0000005: Access violation writing location 0xCDCDCE29.
c++
arrays
pointers
multidimensional-array
datagrid
asked on Stack Overflow Sep 23, 2020 by Jay • edited Sep 28, 2020 by Jay

1 Answer

0

In the presented code, memory has been allocated for Grid*** and Grid** but not for Grid* also the grid itself has never been initialized. So at the last level, pointer array[x][y] holds a meaningless value which possibly points to some where irrelevant, so the Access violation errors!

you should first allocate and possibly initialize the last level pointers like this:

array2D[i][j] = new Grid;

And only then try to access its elements like:

array2D[i][j]->x=6;
array2D[i][j]->y =5;

Also don't forget to correct :

    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)

Another solution is to simply delete one * from the code and put a default constructor in order to avoid construction loop, like below: Grid.h

class Grid
{
public:
    Grid() = default;
    Grid(int);

private:
    int x;
    int y;
    int row;
    int col;
    Grid** array2D;
};

Grid.cpp

Grid::Grid(int)
{
    row = 32;
    col = 30;
    x=0;
    y=0;

     // Allocate memory to point to.
    array2D = new Grid*[row];
    for (int i = 0; i < row; i++) {
        array2D[i] = new Grid[col];
        }

    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            (array2D[i][j]).x=6;
            (array2D[i][j]).y =5;
       }
    }
}

Sample usage:

int main()
{
    Grid grid(0);
    std::cout<<"the end" << std::endl;
    return 0;
}
answered on Stack Overflow Sep 23, 2020 by AKL • edited Sep 23, 2020 by AKL

User contributions licensed under CC BY-SA 3.0