user1887990
user1887990

Reputation: 101

Strange behavior of pointer to array in C++

I wrote this program which uses recursion to calculate the determinant of a matrix. I have a problem with the function build_new_matrix (which is not recursive) because it changes the variable old_mat, although I can't see why!

#include <iostream>
#include <cstring>
using namespace std; 

int * new_mat = new int[];
int calculate_det_small (int matrix [4]){     //calculate determinant of a 2x2 matrix
    int res = ((matrix[0])*(matrix[3]))-((matrix[1])*(matrix[2]));
    return res;
};

int * build_new_matrix (int* old_mat, int rows, int minor){  //return the minor of the matrix

    int l=0;
    for (int i=rows; i<(rows*rows); i++){
        cout<<old_mat[i]<<" ";
        if ((i-minor) % rows !=0){
            new_mat [l] = old_mat[i] ; ///////////////////error!!!!!!!!
            l++;
        }
    };
    return new_mat;
};

int calculate_det (int rows, int matrix[]) {  //calculate determinant of a bigger matrix
    int c,o;
    if (rows==2){
        return calculate_det_small (matrix);
    }
    else {
        int result=0;
        for (int i=0; i<rows;i++){

            int* cur_matrix = build_new_matrix(matrix,rows,i);
            if (i%2==0){
                 c = matrix[i];
                result+= ((matrix[i])*(calculate_det((rows-1),cur_matrix)));
            }
            else{
                 o =matrix[i];
                result-= ((matrix[i])*(calculate_det((rows-1),cur_matrix)));
            }
        };
    return result;
    }
};

void main(){

    int mat[16] = {1,2,3,4,5,6,7,8,9, 10, 11, 12, 10, 14 ,15, 16};

    int determinanta = calculate_det(4,mat);


}

Upvotes: 0

Views: 91

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254471

Because, after the first recursion, old_mat points to the same array as the global new_mat; so writing to new_mat overwrites the old matrix. If you're going to do it this way, you'll need to allocate memory for a new matrix at each recursion depth.

Also, new int[] makes no sense, and shouldn't compile. You need to specify the array size.

Upvotes: 2

Dialecticus
Dialecticus

Reputation: 16761

int * new_mat = new int[];

This line makes no sense. You allocate array with zero elements. Does that even compile?

Upvotes: 0

Related Questions