I've been converting my procedural MATLAB code into OO C++ and it has been quite the learning experience thus far. The error I'm getting is a "0xC0000005: Access violation writing location 0xFDFDFE05", and am not sure what this means.
The following is my MATLAB code, which works:
ms = 0;
for s = 1:Nx
for m = 1:Ny
ms = ms + 1;
np = 0;
for p = 1:Nx
for n = 1:Ny
np = np + 1;
Xm = (m-0.5)*delta_x;
Ys = (s-0.5)*delta_y;
Xa = (n-1)*delta_x;
Xb = n*delta_x;
Ya = (p-1)*delta_y;
Yb = p*delta_y;
a = (Yb-Ys);
b = (Xb-Xm);
c = (Ya-Ys);
d = (Xa-Xm);
numA = b + sqrt(b.^2+a.^2);
denA = d + sqrt(d.^2+a.^2);
numB = a + sqrt(b.^2+a.^2);
denB = c + sqrt(b.^2+c.^2);
numC = d + sqrt(d.^2+c.^2);
denC = b + sqrt(b.^2+c.^2);
numD = c + sqrt(d.^2+c.^2);
denD = a + sqrt(d.^2+a.^2);
A = a.*log(numA./denA);
B = b.*log(numB./denB);
C = c.*log(numC./denC);
D = d.*log(numD./denD);
Z1(ms,np) = (A+B+(C+D))*k;
end
end
end
end
The following is the function, located in a cpp-file outside of main.cpp. (EDIT: I made the changes suggested in the comments below, and it now works as expected.)
double** zMatrix(double deltaX, double deltaY, double Nx, double Ny) {
double** Z = allocateMatrix(Nx*Nx, Ny*Ny);
int ms = 0;
for (int s = 0; s < Nx; s++)
{
for (int m = 0; m < Ny; m++)
{
int np = 0;
for (int p = 0; p < Nx; p++)
{
for (int n = 0; n < Ny; n++)
{
// Center of each observer patch
double Xm = (m - 0.5) * deltaX;
double Ys = (s - 0.5) * deltaY;
// Source coordinates w/ corner (Xa, Ya) @ the origin (0, 0)
// Lowest order basis function set:
double Xa = (n - 1) * deltaX;
double Xb = n * deltaX;
double Ya = (p - 1) * deltaY;
double Yb = p * deltaY;
// Building analytical solution
double a = (Yb - Ys);
double b = (Xb - Xm);
double c = (Ya - Ys);
double d = (Xa - Xm);
double numA = b + hypot(b, a); // sqrt(b*b + a * a);
double denA = d + hypot(d, a); // sqrt(d*d + a * a);
double numB = a + hypot(b, a); // sqrt(b*b + a * a);
double denB = c + hypot(b, c); // sqrt(b*b + c * c);
double numC = d + hypot(d, c); // sqrt(d*d + c * c);
double denC = b + hypot(b, c); // sqrt(b*b + c * c);
double numD = c + hypot(d, c); // sqrt(d*d + c * c);
double denD = a + hypot(d, a); // sqrt(d*d + a * a);
double A = a * log(numA / denA);
double B = b * log(numB / denB);
double C = c * log(numC / denC);
double D = d * log(numD / denD);
Z[ms][np] = (A + B + (C + D)) * k;
np++;
}
}
ms++;
}
}
return Z;
}
Here is my allocate matrix function:
double** allocateMatrix(double width, double height)
{
// allocate the matrix
double** zMatrix = new double*[width];
for (int i = 0; i < width; i++)
{
zMatrix[i] = new double[height];
}
return zMatrix;
}
And then in main.cpp, I just call it like this:
double** Z = zMatrix(deltaX, deltaY, Nx, Ny);
I'm (usually) pretty good and debugging, but this one isn't really giving me much to work with.
Here's a capture of the variables during runtime, where I think the error points to, i.e. Z[ms]: