-1

I have created a class that works for a static array, but when I try to use it with my dynamic array, it is not working. (To not fill this page with a long long code, I just copied one function of my class)

I think that my dynamic array is not properly created, but I am not sure of where I am wrong.

Even thou here I am just using arrays of 10 X 10 x 4 in my project i will need to use arrays of around 1500 X 1500 X 4. Is my approach accurate or would using vectors be better, if so, how can I implement it??

Here is my code.

#include <iostream>
const int N = 10;
const int M = 10;
const int O = 4;
const double gama =1.4;


class Fluid
{
public:

    void SetInitialConditions(double *** Array_U, int initialX, int finalX, int initialY, int finalY, double rho, double u, double v, double p)  // initial conditions
    {
        for (int i = initialX; i<=finalX; i++)
            for (int j = initialY ; j<=finalY; j++) {
                Array_U[i][j][0]=rho;
                Array_U[i][j][1]=rho*u;;
                Array_U[i][j][2]=rho*v;
                Array_U[i][j][3]= (p/(gama-1)) + 0.5*rho*(u*u+v*v);

            }

        }
};
int main ()
{
    double ***my3dArray = new double**[M];
    for(int i = 0; i < M; i++)
    {
        my3dArray[i] = new double *[N];
        for(int j = 0; j < N; j++)
        {
            my3dArray[i][j] = new double[O];
        }
    }
    for(int i = 0; i < M; i++)
    {
        for(int j = 0; j < N; j++)
        {
            for (int k = 0; k< O; k ++) {
                my3dArray[i][j][k] = NULL;
            }
        }
    }


    Fluid test;
    test.SetInitialConditions(my3dArray, 0, M, 0, N, 0, 1, 2, 3);
    std::cout << my3dArray[1][1] << my3dArray [2][2] << std::endl;

}
heri-salmas
  • 103
  • 2
  • 12

2 Answers2

1
const int N = 10;
const int M = 10;
const int O = 4;

If N and O are indeed constants, you can allocate the 3D array in one big chunk:

double (*my3dArray)[N][O] = new double[M][N][O];
// ...
delete[] my3dArray;

This will be more efficient, both in regards to memory consumption and execution time.

You can find more information than you would ever want to know about multidimensional arrays here.

Community
  • 1
  • 1
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
1

Your problem seems to be this:

for (int i = initialX; i<=finalX; i++)
        for (int j = initialY ; j<=finalY; j++) {

You are writing beyond the boundaries of the array. Use <, not <=

    for (int i = initialX; i<finalX; i++)
        for (int j = initialY ; j<finalY; j++) {

However having said that, a vector would be much cleaner.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45