dimanche 7 octobre 2018

Why does the pointer in this program is changed?

The program is designed to obtain a 2d array from a particular function, the array itself will be used as an input for other function. However, when the program showed the pointer of the 2d array, it displayed a different pointer for both cases. What is wrong?

int main(){
    int x = 10;
    int y = 2;
    double dx = 0.1;
    double dy = 0.1;
    double NorthBC = 0.1;
    double SouthBC = 0.2;
    double WestBC = 0.3;
    double EastBC = 0.4;

    double** a = CaseDefinition(x, y, NorthBC, SouthBC, WestBC, EastBC);

    double** results = ExplicitMethod(&a[0][0], x+2, y+2, dx, dy);
return 0;
}

CaseDefinition function definition is,

double** CaseDefinition(int meshx, int meshy, double NorthBC, double 
SouthBC, double WestBC, double EastBC){
double** Case = 0;
Case = new double*[meshy+2];
for (int i=0; i<meshy+2; i++){
    Case[i] = new double[meshx+2];
    for (int j=0; j<meshx+2; j++){
        Case[i][j] = 0;
    }
}
for (int i=0; i<meshy+2; i++){
    for (int j=0; j<meshx+2; j++){
        if (i == 0 && j > 0 && j < meshx+1){
            Case[i][j] = SouthBC;
        }
        if (i == meshy+1 && j > 0 && j < meshx+1){
            Case[i][j] = NorthBC;
        }
        if (j == 0 && i > 0 && i < meshy+1){
            Case[i][j] = WestBC;
        }
        if (j == meshx+1 && i > 0 && i < meshy+1){
            Case[i][j] = EastBC;
        }
        std::cout<<&Case[i][j]<<" ";
    }
    std::cout<<std::endl;
}
std::cout << "Case Definiton ends" << std::endl;
std::cout<<std::endl;
return Case;

}

while ExplicitMethod function definition is,

#include <cmath>

double** ExplicitMethod(double* Case, int xdimCase, int ydimCase, double dx, 
double dy){
//variables definition
std::cout<<"Explicit Method Starts!!"<<std::endl;
double** UpdatedCase;
double** OldCase;
double relaxation_param = 0.8;
double error = 0;

UpdatedCase = new double*[ydimCase];
OldCase = new double*[ydimCase];
for (int i=0; i<ydimCase; i++){
    UpdatedCase[i] = new double[xdimCase];
    OldCase[i] = new double[xdimCase];
}

for (int i = 0; i < ydimCase; ++i){
    for (int j = 0; j < xdimCase; ++j)
        std::cout<<&Case[i*xdimCase + j]<<" ";
    std::cout<<std::endl;
}
std::cout<<std::endl;

The result is something like this enter image description here The array a is the output of the first function and as the input of function ExplicitMethod. Other inputs are fine. As you can see, the printed pointers are not same as it should be. What can be the cause of the problem? How can I solve it?

Aucun commentaire:

Enregistrer un commentaire