>I am working on trying to get it to work for 3 dimensions + but I would like to see how others implement this.
Just keep following the pattern.
<strong>#include</strong> <iostream>
<strong>void</strong> <strong>foo</strong>(std::size_t x, std::size_t y, std::size_t z)
{
<strong>int</strong> q = 0, ***array;
// Create and initialize dynamic 3-D "array"
array = <strong>new</strong> <strong>int</strong>**[x];
<strong>for</strong> ( std::size_t i = 0; i < x; ++i )
{
array[i] = <strong>new</strong> <strong>int</strong> *[y];
<strong>for</strong> ( std::size_t j = 0; j < y; ++j )
{
array[i][j] = <strong>new</strong> <strong>int</strong>[z];
<strong>for</strong> ( std::size_t k = 0; k < z; ++k )
{
array[i][j][k] = ++q; // initialize with something
}
}
}
// Show elements
<strong>for</strong> ( std::size_t i = 0; i < x; ++i )
{
<strong>for</strong> ( std::size_t j = 0; j < y; ++j )
{
<strong>for</strong> ( std::size_t k = 0; k < z; ++k )
{
std::<strong>cout</strong> << "array[" << i << "][" << j << "][" << k
<< "] = " << array[i][j][k] << std::<strong>endl</strong>;
}
}
}
// Free memory
<strong>for</strong> ( std::size_t i = 0; i < x; ++i )
{
<strong>for</strong> ( std::size_t j = 0; j < y; ++j )
{
<strong>delete</strong>[] array[i][j];
}
<strong>delete</strong>[] array[i];
}
<strong>delete</strong>[] array;
}
<strong>int</strong> <strong>main</strong>()
{
<strong>foo</strong>(2,3,4);
<strong>return</strong> 0;
}
/* my output
array[0][0][0] = 1
array[0][0][1] = 2
array[0][0][2] = 3
array[0][0][3] = 4
array[0][1][0] = 5
array[0][1][1] = 6
array[0][1][2] = 7
array[0][1][3] = 8
array[0][2][0] = 9
array[0][2][1] = 10
array[0][2][2] = 11
array[0][2][3] = 12
array[1][0][0] = 13
array[1][0][1] = 14
array[1][0][2] = 15
array[1][0][3] = 16
array[1][1][0] = 17
array[1][1][1] = 18
array[1][1][2] = 19
array[1][1][3] = 20
array[1][2][0] = 21
array[1][2][1] = 22
array[1][2][2] = 23
array[1][2][3] = 24
*/ Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314