我正在编写一个程序来执行一组数值方法。为此,我需要创建任意大小的矩阵并将它们放在函数之间。显然,如果我在使用后不清理创建的矩阵,我会得到相当大的内存泄漏。
double** MatrixInitialize(int m, int n)//generates a A[m][n] matrix
{
int i = 0, j = 0;
double** B = new double*[m];
for (m = 0; m < n; m++)
{
B[m] = new double[n];
}
for (j = 0;j<m;j++)
for (i = 0; i < n; i++)
{
B[i][j] = 0;
}
return(B);
}
int main()
{
double** MatrixA;
MatrixA=MatrixInitialize(2,2)
//Some manipulation on MatrixA is done here
delete[] MatrixA[0]; delete[] MatrixA[1]; delete[] MatrixA;
return 0;
}
一旦调用delete []行,我就会抛出访问冲突消息并且必须中断。还有其他一些程序我必须通过删除这些指针吗?
答案 0 :(得分:0)
让语言为你服务
int main()
{
int ysize = 10;
int xsize = 5;
std::vector<std::vector<double>> B(ysize, std::vector<double>(xsize, 0));
for (int y = 0; y < ysize; y++)
{
for (int x = 0; x < xsize; x++)
{
B[y][x] = 1.23;
}
}
for (int y = 0; y < ysize; y++)
{
for (int x = 0; x < xsize; x++)
{
std::cout << B[y][x] << " ";
}
}
std::cout << "\n";
}