我正在使用多维数组,但出现异常,我搜索了很多但发现我正在使用相同的答案,当我尝试分配 matriz[i] = new double[n] 时异常跳转.我已经尝试了评论和未评论的解决方案,但没有成功。
void interpol(double *arr_x, double *arr_y, int n, double *results) {
//double** matriz = new double*[n];
double** matriz;
matriz = (double**) malloc(n * sizeof(double*));
for(int i = 0; i < n; i++){
//matriz[i] = new double[n+1];
matriz[i] = (double*) malloc(n+1 * sizeof(double));
for(int j = 0; j < n; j++) {
matriz[i][j] = pow(arr_x[i],j);
}
matriz[i][n] = arr_y[i];
}
gaussiana(matriz, n, results);
}
--- 编辑---
函数 gaussiana 工作正常,因为我已经在这个函数之外进行了测试。异常抛出在: //矩阵[i] = new double[n]; matriz[i] = (double*) malloc(n * sizeof(double));
n 永远不会超过 10。
抛出的异常是:
First-chance exception at 0x00071c4d in Interpolacion.exe: 0xC0000005: Access violation reading location 0x00000000. Unhandled exception at 0x774b15de in Interpolacion.exe: 0xC0000005: Access violation reading location 0x00000000. The program '[8012] Interpolacion.exe: Native' has exited with code -1073741819 (0xc0000005).
----编辑---- 我终于让它工作了,问题不在矩阵中,但在 arr_x/arr_y 中,外部例程发送了错误的数据(奇怪的是错误和堆栈跟踪总是让我引用新的双 [n] 赋值)
最佳答案
如果你想使用 std::vector
路线,您可以使用类似下面的内容(未经测试,仅作为指南显示)。请记住 std::vector<std::vector<double> >
与 double **
不兼容, 所以你的 gaussiana
可能需要重写函数以接受新类型。:
// Include the header!
#include <vector>
// Be careful about the use of "using namespace std", I'm only using it here
// because it's a small example
using namespace std;
vector<vector<double> > matriz;
for (int i = 0; i < n; i++)
{
// Create a new vector "v" with n+1 elements
vector<double> v(n + 1);
// fill this vector
for (int j = 0; j < n; j++)
v[j] = pow(arr_x[i], j);
v[n] = arr_y[i];
// add it to the matrix
matriz.push_back(v);
}
关于c++ - C++ 中的动态矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10117981/