Memory allocation recursive algorithm

I've been working on a matrix class and I ran into a problem in writing my matrix class. I keep getting 0 as a determinant and with some debugging, I found that I was losing allocated data or something similar. This algorithm I'm pretty sure works because I used this same algorithm in a function I made in python. http://stackoverflow.com/questions/21220504/matrix-determinant-algorithm-c That's where I found the algorithm. If you need my full class I can provide it but I figured this would be easier to look at.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*template <class T>
double Matrix<T>::det(T* array, size_t dim, bool recursion)*/

double det(T* array = NULL, size_t dim = 0, bool recursion = false) {
	
	if (recursion == false) {
		if (m != n) {
			return 0;
		}
		else if (n == 1) {
			return *matrix;
		}
		else {
			array = matrix; // matrix is a pointer to an array
			dim = n; // n is the matrix size
		}
	}

	if (dim == 2) {
		std::cout << (*(array+4));
		return ((*(array)) * (*(array+4)) - (*(array+2)) * (*(array+1)));
	}
	else {
		double determinant = 0;
		size_t p,h,k,i,j,x = dim - 1;
		T temp[x][x];
		
		// Use expansions of minors to compute the matrix determinant 
		for (p=0;p<dim;p++) {
			h = 0;
			k = 0;
			for (i=1;i<dim;i++) {
				for (j=0;j<dim;j++) {
					if (j == p) 
						continue;
					temp[h][k] = *(array+dim*i+j);
					k++;
					if (k == x) {
						h++;
						k = 0;
					}
				}
			}
			
			// Allocate memory for temp
			T* point = (T*)malloc(x*x*sizeof(T));
			for (i=0;i<x;i++) {
				for (j=0;j<x;j++) {
					*(point+x*i+j) = temp[i][j];
					std::cout << *(point+x*i+j) << '\t';
				}
				std::cout << std::endl;
			}
			std::cout << std:: endl;
			determinant += (*(array+p)) * pow(-1,p) * det(point,x,true); // Recursive
			
			// Free memory for temp
			free(point);
			point = NULL;
		}
		return determinant;
	}
}
on lines 20,21 should be array+3, not array+4
Thank You! That was it.
Topic archived. No new replies allowed.