Reputation: 113
I am trying to make that my arrays created with boost work with a function. I wrote the following code, but its not working. How can I make so, that my array is read by my functions? In the previous version of this code, I just defined my array like double U[N+1][4]. and it worked. What am I doing wrong while using boost?
#include "boost/multi_array.hpp"
#include <cassert>
#include <iostream>
#include <cmath>
#include <time.h>
int const N=400;
int const x1=0;
int const x2=1;
int const gammaValue=1.4;
void Output(double U[N][3])
{
double x,dx;
dx=(double(x2-x1))/double(N);
FILE *fp;
double rho,u,p;
fp=fopen("result.dat","w+");
fprintf(fp,"%2.30s\n %20.60s\n %20.18s\t %2.3d\t %2.18s\t ","TITLE = \"1D-EULER.dat \"","variables = \"x\", \"rho\", \"u\", \"p\"","zone i=",N+1,"f=point\n");
for(int n=0;n<N+1;n++)
{
x=x1+n*dx;
rho=U[n][0];
u=U[n][1]/U[n][0];
p=(gammaValue-1)*(U[n][2]-0.5*U[n][0]*u*u);
fprintf(fp,"%20.5f\t%20.5f\t%20.5f\t%20.5f\n",x,rho,u,p);
}
fclose(fp);
}
int main () {
// 3 x 4 x 2
typedef boost::multi_array<double, 2> array_type;
typedef array_type::index index;
array_type A(boost::extents[N][3]);
int values = 0;
for(index i = 0; i != N; ++i) {
for(index j = 0; j != 3; ++j){
A[i][j] = i+j;
}
}
Output(A);
return 0;
}
Upvotes: 0
Views: 1128
Reputation: 3348
Why not just change the signature of the Output function? Move the array_type
typedef to the top of your file and then change the Output function to this:
void Output( array_type& U )
Or, better yet, make the parameter const
. Here's some code:
#include <boost/multi_array.hpp>
#include <iostream>
typedef boost::multi_array< double, 2 > array_type;
void Output( const array_type& arr )
{
std::cout << "here" << std::endl;
}
int main( int argc, char ** argv )
{
array_type arr;
Output( arr );
return 0;
}
This does nothing but demonstrate the principal of changing the function signature appropriately.
Upvotes: 1
Reputation: 8020
Use the multi_array's member function data()
, it returns a pointer to the beginning of the contiguous block that contains the array's data. Once you get the address of the first element, you can get others since you already know the dimension of the array.
double * p = A.data();
double (*array)[3] = (double (*)[3])p;
Output(array);
Upvotes: 2