我一直在将程序MATLAB代码转换为OO C ++,到目前为止,这已经是相当不错的学习经验。我收到的错误是“ 0xC0000005:访问冲突写入位置0xFDFDFE05”,并且不确定这是什么意思。
以下是我的MATLAB代码,可以正常工作:
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
以下是该函数,位于main.cpp之外的cpp文件中。 (编辑:我进行了以下注释中建议的更改,并且现在可以按预期运行。)
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;
}
这是我的分配矩阵函数:
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;
}
然后在main.cpp中,我这样称呼它:
double** Z = zMatrix(deltaX, deltaY, Nx, Ny);
我(通常)非常擅长调试,但实际上并没有给我太多帮助。
这里是运行时变量的捕获,我认为错误指向这里,即Z [ms]:
答案 0 :(得分:1)
您正在将(width*height)
x (width*height)
元素写入width
x height
矩阵。因此,您的写作超出了范围。
我想您可以使用以下方法解决此问题:
double** Z = allocateMatrix(width*height, width*height);