When I do the following:
float name[512][512][3]
I get this big error which causes me to break. I'm using Visual Studio.
I noticed simply putting "static" in front causes the error to go away, but I want this to be an instance field. I'm not sure why this is happening -- the array isn't that big and I have a powerful machine.
Trying [512][512] breaks me, but [256][512] is totally fine.
I'm at my wit's end! Help please :)
The array is 3 MB (on most implementations of float). Objects of such size should only be allocated dynamically—3 MB is way too much for residing on the stack.
You have two options: one is to keep your class as-is, and make sure you only ever allocate it dynamically (using new, owned in a smart pointer).
The other, which I would prefer, is to use std::vector<float> instead of a 3-dimensional array, and implement the indexing around it as accessor functions. You could even wrap this vector & accessors in a class of their own, and use that as the type of your name data member.
The second option guarantees that the 3 MB of data will never reside in non-dynamic memory.
Here's one possible sketch of such a 3D-accessible vector:
template <class T, size_t Dim1, Dim2, Dim3>
class Array3d
{
std::vector<T> data;
public:
Array3d() : data(Dim1 * Dim2 * Dim3) {}
T& at(size_t idx1, size_t idx2, size_t idx3)
{ return data[idx1 * Dim2 * Dim3 + idx2 * Dim3 + idx3); }
T at(size_t idx1, size_t idx2, size_t idx3) const
{ return data[idx1 * Dim2 * Dim3 + idx2 * Dim3 + idx3); }
};
A more basic alternative would be to just dynamically allocate the array itself:
using Array2d = std::array<std::array<float, 3>, 512>;
std::unique_ptr<Array2d[]> name{new Array2d[512]};
name[i][j][k] = 42.0f;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With