0

I am trying make make a basic chunk loading system using two dimensional arrays, and PNG images. I was just wondering if it is possible to create a uninitialized array for example;

Chunk[][] chunks;

and then initialize it based on the size of the PNG image and use different rgb pixels to stand for different tiles.

Say the immage is 15x25, is it possible to initialize the two dimensional array with a somewhat like this?

chunks = new Chunk[15][25];

Or should I go about making a large array and just having the index's that aren't set be a VOID tile I could just simply make.

Thank you everybody for your help!

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
Ethan
  • 1
  • 2
    Possible duplicate of [How do I declare a 2d array in C++ using new?](https://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new). I would recommend either using `std::array, 25>` or following your own suggestion of a 15*25 1D array. – Max Langhof Jan 30 '19 at 16:08
  • You could use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector/vector), `std::vector> chunks(15, std::vector(25));` – George Jan 30 '19 at 16:12
  • `Chunk[][] chunks;` is not legal C++, all but the first dimension must be specified using a compile time constant. Use a vector (1D) or a vector of vectors (2D) anything but a 2D array. – john Jan 30 '19 at 16:16
  • `chunks = new Chunk[a][b]` is hard to achieve. The size of an array is constant, and should be defined at compile-time (though, GCC does have an expansion that allows a `const int` to determine the size). Reading this PNG image, or files in general, cannot occur at compile-time. Therefore, you should use other containers, such as `std::vector`, where the size does not have to be predetermined. – Lourens Dijkstra Jan 30 '19 at 16:19
  • Neither of those duplicates are correct, the problem calls for a contiguous block of memory with dynamic dimensions. – Galik Jan 30 '19 at 16:48
  • You can use this technique, basically a single dimension array with a two dimensional accessing scheme: https://stackoverflow.com/questions/52436723/sorting-2-d-array-in-c-using-inbuilt-stdsort-function/52436916#52436916 – Galik Jan 30 '19 at 16:51
  • Another example of the technique: https://stackoverflow.com/a/53038618/3807729 – Galik Jan 30 '19 at 16:53

1 Answers1

0

C++ does not support variable-length arrays like C does. Modern, idiomatic C++ also discourages raw arrays over std::vector or std::array, which can also be used in 2D, like so:

std::size_t x = /* get X dimension */
std::size_t y = /* get Y dimension */
std::vector<std::vector<Chunk>> chunks(x, std::vector<Chunk>(y));

std::vector also has the advantage of automatic size management and permissibility of a variable-length initializer, unlike std::array, which, to my knowledge, only permits constants during initialization.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85