0

I've searched and searched but haven't found anything that really clears up my confusion.

I'm representing a grid, and have two classes, e.g.:

class Term {
   ...
};

class GridPoint{
   Term a;
   Term b;
   Term c;
   ...
};

I would like to have a large, fixed-size array on the heap, where each element of the array is a GridPoint, itself containing multiple Terms.

However, the following example will not compile:

GridPoint* pGrid = new GridPoint[100][100];

According to gcc:

error: cannot convert ‘GridPoint (*)[100]’ to ‘GridPoint*’ in initialization

trincot
  • 317,000
  • 35
  • 244
  • 286
nathanvy
  • 145
  • 7

1 Answers1

-1

First I would like to suggest not using new and delete in modern C++, instead use smart pointers or containers from the standard library that encapsulates this as e.g. std::vector.

That being said, to get your example to work you have to initialize an array of arrays in a loop like so:

GridPoint** pGrid = new GridPoint*[100];
for (std::size_t i = 0; i != 100; ++i) {
    pGrid[i] = new GridPoint[100];
}

// Do something...

for (std::size_t i = 0; i != 100; ++i) {
    delete[] pGrid[i];
}
delete[] pGrid;

For a better alternative simply use std::array or std::vector:

std::array<std::array<GridPoint, 100>, 100> pGrid;

Note: std::array encapsulates a static array that it uses to store its data. This means that if you allocate a std::array object with automatic storage duration its data will not be dynamically allocated (the data will not be on the "heap").

std::vector will however store its data using dynamic allocation.

Felix Glas
  • 15,065
  • 7
  • 53
  • 82