Reputation: 227
I would like to pass a series of 2D-arrays to a function, which then saves it to a file. My "saving function" is as follows: (Question marks indicate I don't know what the hell I am doing.)
void saveArray(double* z(?),double* u1(?),double* u2 (?),double* theta (?), int row,
int column)
{
ofstream output("data.csv");
for(int j=0;j<row;++j)
for(int i=0;i<column;i++)
{
output<<setprecision(32)<<z[j]<<","<<setprecision(32)<<u1[j][i]<<","
<<setprecision(32)
<<u2[j][i] <<","<<setprecision(32)<<theta[j][i]<<endl;
}
z is : z[30000],u1,u2 and theta are [101][30000] 2D-arrays.
Please let me know if this is confusing and I can post the entire code.
Upvotes: 0
Views: 1051
Reputation: 103751
I find it's much easier to deal with 2d arrays by treating them as 1d arrays, at least when passing them as parameters.
void saveArray(double* z, double* u1, double* u2, double* theta, int row, int column)
{
ofstream output("data.csv");
for(int j=0; j<row; ++j)
for(int i=0; i<column; i++)
{
int offset = j * column + i;
output <<setprecision(32)<<z[j]<<","
<<setprecision(32)<<u1[offset]<<","
<<setprecision(32)<<u2[offset] <<","
<<setprecision(32)<<theta[offset]<<endl;
}
}
When you call it, be sure to dereference your 2d arrays:
saveArray(z, *u1, *u2, *theta, 101, 30000);
You could also do it another way where you can pass the arrays by reference, and you don't need to pass the size. This will only work if you have the actual arrays, not just pointers to them:
template<size_t R, size_t C>
void saveArray(double (&z)[C], double (&u1)[R][C], double (&u2)[R][C], double (&theta)[R][C])
{
ofstream output("data.csv");
for(int r=0; r<R; ++r)
for(int c=0; c<C; ++c)
{
output <<setprecision(32)<<z[c]<<","
<<setprecision(32)<<u1[r][c]<<","
<<setprecision(32)<<u2[r][c] <<","
<<setprecision(32)<<theta[r][c]<<endl;
}
}
Then you would just call it like this:
saveArray(z, u1, u2, theta);
Upvotes: 2