Re: need help in dynamic memory alloction of multi-dimensional array

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Alex Blekhman schrieb:
Allen Maki wrote:
When I used the 2 following lines in a simple code, the
code will compile with no error:

long (*pprime)[max2];

pprime = new long[max][max2];

But if I separate the two lines by putting the first in a
class
and the second line in the constructor of the same class
I will have the under mentioned error messages.

Can you tell me what is wrong?

Stop reinventing the wheel. Use std::vector:

-----------------
typedef std::vector< long > vector1d;
typedef std::vector< vector1d > vector2d;

const size_t rows = 3;
const size_t cols = 4;

vector2d v2d;

v2d.resize(rows);

// initialize 2d array with zeros
//
for(vector2d::iterator it = v2d.begin();
it != v2d.end();
++it)
{
(*it).resize(cols);
}

// now you can access some element
v2d[0][0] = 42;
-----------------

If you want to avoid `for' statement and make code more
laconic, then there are handy STL functors. Here the 2d
array is initialized in one statement:

-----------------
...
// initialize 2d array with zeros
//
std::for_each(v2d.begin(), v2d.end(),
std::bind2nd(
std::mem_fun_ref(&vector1d::resize), cols));


What's wrong with this :

vector2d v2d(rows, vector1d(cols));


That's _one_ (readable) line.

Stefan
--
Stefan Naewe
naewe.s_AT_atlas_DOT_de
.



Relevant Pages