Suppose I have a grid of squared defined like so in a class:
Square (* grid)[];
This, oddly, seems to compile fine. I would think it would error because the compiler doesn’t know how big the array is?
Anyways,
it means it is a pointer to an array. Then to initialize it, I do:
grid(new Square[width * height])
This isn’t accepted by the compiler, because the new statement returns a pointer to squares rather than a pointer to an array of squares. It makes sense that it does that. Now, is there a simple way to accomplish what I’m asking, other than just declaring Square ** grid and looping through it and doing separate allocations for each column of the 2D array?
That’s declaring a pointer to an array, not an array; it’s fine to declare a pointer to any incomplete type, including an array of unknown size. However, it’s quite an unusual thing to do, and not what you want for a dynamic array.
The easiest dynamic array to use is:
initialised as
If you really want to manage the memory yourself, then change your pointer-to-array to a pointer-to-object:
initialised as
A pointer can point to either a single object, or the start of an array; if it does point to an array, then you can use
[]on it just like with a non-dynamic array. Make sure you deallocate it (delete [] grid;) once you’ve finished with it.If you want a 2-dimensional array, it’s often easiest to use a 1-dimensional array, and wrap the necessary arithmetic in an accessor function: