By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,652 Members | 1,694 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,652 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
wrote in news:13************************@posting.google.com 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[i][j] = (i + 1) * (j + 1);
}
}

for (i = 0; i < 10; ++i)
{
for (j = 0; j < 10; ++j)
{
cout << setw(4) << a[i][j];
}
cout << endl;
}
}
Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.