Search code examples
c++multidimensional-arraydynamic-arrays

Dynamic matrix in C++


I am working with a multidimensional array but i get an exception, i have searched a lot but i find the same answer i'm using, the exception jumps when i try to allocate matriz[i] = new double[n]. I have tried both the commented and uncommented solutions with no luck.

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);
}

--- EDIT---

The function gaussiana is working fine, since i have tested outside this function. The exception is thrown in either: //matriz[i] = new double[n]; matriz[i] = (double*) malloc(n * sizeof(double));

n is never more than 10.

The exception thrown is:

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).

----EDIT---- I finally got it working, the issue was not in matriz, but with arr_x/arr_y, the external routine was sending the data wrong (oddly the error and the stacktrace always referred me to the new double[n] assignation)


Solution

  • If you want to use the std::vector route, you can use something like below (untested, shown just as a guide). Keep in mind that std::vector<std::vector<double> > is not compatible with double **, so your gaussiana function might need to be rewritten to accept the new type.:

    // 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);
    }