Hi. I have to create a 3-Dimensional array, wich gets allocated at object creation. I've done such stuff before with normal arrays.
typedef unsigned char byte; // =|
byte ***data;
Hi. I have to create a 3-Dimensional array, wich gets allocated at object creation. I've done such stuff before with normal arrays.
typedef unsigned char byte; // =|
byte ***data;
Well, as a first guess to how you might want to handle this:
for(int i=0; i < length; ++i){
data = new char**[size];
for(int j = 0; j < anotherLength; ++j){
data[i] = new char*[anotherSize];
...
get the idea? Personally I'd go with vector
's of vector
s with the final component being a string
.
If you're using C++
, I strongly advise you using std::vector
instead of raw arrays.
Something like:
std::vector<std::vector<std::vector<char> > > data(3, std::vector<std::vector<char> >(3, std::vector<char>(3, 0)));
Will create a 3x3x3 array of char
s, all initialized to 0
.
You can then access the items the same way you would with a char***
:
data[0][0][0] = 1;
Depending on your needs you might also use only one std::vector
and inline your three-dimensional space into it. This would fasten both computation and copy operations, as the values would then be in a contiguous block of memory.
The way you could inline the values depending on your needs, but here is an example:
For a 3 dimensional array like this:
a----b
|\ |\
| d----c
e-|--f |
\| \|
h----g
You might store values like this in memory:
a, b, c, d, e, f, g, h
This require some maths, but if you encapsulate this, you can even achieve the same level of usability of a vector
of vector
of vector
, with much higher performances.
Triple indirection is generally a bad way of doing this unless you really need arrays of arrays (e.g., if the size of array[0]
has to differ from the size of array[1]
). For simple multi-dimensional arrays use something like Boost.MultiArray.
The char*** route will leave you with non-contiguous memory, and this is a major performance problem when things get big. If you must use native arrays I would use a char* and do the following:
const int xDim = ??;
const int yDim = ??;
const int zDim = ??;
char* array = new char[xDim*yDim*zDim];
// Then just create a good indexing scheme.
char getElement(char* array, int x, int y, int z)
{
// ultimately this is not hard to figure out, but I know I will
// screw it up here and I don't have time to test the code.
int element = some function of x,y,z,xDim,yDim,zDim;
return array[element];
}
That is the basicness of it. If you're going to go down this road though, you should really consider wrapping that char* in a class (maybe Array3D) and have getElement as a member function.
Again though, STL might be more appropriate.
In fact I think the only good reason for not using STL would be to ensure a contiguous chunk of memory, which again char*** will not do.