dynamic multidimensional array allocation using one(and only one) 'new' call

I

ip4ram

I have an old set of library,where I used malloc to allocate
multidimensional(2 and 3) arrays,using only one malloc call(using void
pointers).I get the size of the array in run time.Now that I am moving
to C++,I wish to know if it is possible to allocate a
multi-dimensional(say 2 and 3) with just one (and only one) call to
'new'operator.The idea behind this is to have contiguous memory
locations for array data.Thanks in advance,for all your help.

Ram
 
R

Rob Williscroft

wrote in in
comp.lang.c++:
I have an old set of library,where I used malloc to allocate
multidimensional(2 and 3) arrays,using only one malloc call(using void
pointers).I get the size of the array in run time.Now that I am moving
to C++,I wish to know if it is possible to allocate a
multi-dimensional(say 2 and 3) with just one (and only one) call to
'new'operator.The idea behind this is to have contiguous memory
locations for array data.Thanks in advance,for all your help.


Yes, but always prefer using a standard container to calling
new [].

#include <iostream>
#include <ostream>
#include <iomanip>
#include <vector>

template < typename T >
struct vector2d
{
vector2d(std::size_t n = 0) : m_Order(n), data( n * n ) {}
void set_Order(std::size_t n) { data.resize(n * (m_Order = n)); }

T *operator[](std::size_t off)
{
return &(data[off * m_Order]);
}
T const *operator[](std::size_t off) const
{
return &(data[off * m_Order]);
}

private:

std::size_t m_Order;
std::vector< T > data;
};


int main()
{
using namespace std;

vector2d< int > a(10);
int i, j;

for (i = 0; i < 10; ++i)
{
for (j = 0; j < 10; ++j)
{
a[j] = (i + 1) * (j + 1);
}
}

for (i = 0; i < 10; ++i)
{
for (j = 0; j < 10; ++j)
{
cout << setw(4) << a[j];
}
cout << endl;
}
}


Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top