passing arrays to functions in c++
I want to pass an array to a certain function in c++. I wrote the following 开发者_运维技巧code:
#define nmpart 50
void distances( double (&dis)[3][nmpart][nmpart] )
{
... compute distances which are allocated in "dis"
}
double energy()
{
double dis[3][nmpart][nmpart];
distances(dis);
}
This code is working fine when nmpart<800 approximately. The issue is that I would like to have a bigger array let say for nmpart=50000. I have read in this forum that one can use dynamical allocation to overcome this problem. It is not clear for me how could I use dynamical allocation in this situation. Could you give me some hints.
Now, a lot of people (including myself) would never write this code professionally (or otherwise) but it basically answers your question. See below for why I'd never write this professionally.
#define nmpart 50
void distances( const double ***dist)
{
... compute distances which are allocated in "dis"
}
double energy()
{
double ***dis;
// allocate dis
dis = new double**[3];
for(int i=0;i<3;++i)
{
dis[i] = new double*[nmpart];
for(int j=0;j<nmpart;++j)
{
dis[i][j] = new double[nmpart];
}
}
// code where you populate dis
// HERE
distances(dis);
// deallocate dis
for(int i=0;i<3;++i)
{
for(int j=0;j<nmpart;++j)
{
delete [] dis[i][j];
}
delete [] dis[i];
}
delete [] dis;
}
Basically, I'd never write this (other than for instructional purposes) because if there's an exception thrown somewhere in this function, then it's going to leak memory. The best thing to do would be to wrap the heap allocations and deallocations (with new
and delete
respectively) in a class and put that class on the local stack inside your energy()
function.
Ideally you'd do something like this:
#define nmpart 50
void distances( const distClass &dis)
{
... compute distances which are allocated in "dis"
}
double energy()
{
distClass dis;
// this allocate wraps the for loops with the new []'s above
dis.Allocate(3, nmpart , nmpart);
// populate dis HERE
distances(dis);
// when dis goes out of scope its destructor
// is called, which wraps the for loops with the delete []'s
}
You can use std::vector instead. This allow dynamic allocation.
void distances( std::vector< std::vector< std::vector<double> > > const& dis )
{
... compute distances which are allocated in "dis"
}
double energy()
{
std::vector< std::vector< std::vector<double> > > dis;
distances(dis);
}
精彩评论