Error in program C (calculation of determinants)

2
#include <stdio.h>
#include <math.h>

void zerar(int n,int m[][n]) {
    int i, j;
    for (i=0; i<n; i++) {
        for (j=0; j<n; j++) {
            m[i][j] = 0;
        }
    }
}

void printm(int n, int matriz[][n]) {
    int i,j;
    for (i=0; i<n; i++) {
        for (j=0; j<n; j++) {
            printf("\t%d", matriz[i][j]);
        }
        printf("\n");
    }
}

int det(int n, int matriz[][n]) {
    int i, j, k, x, y, soma=0, aux[10][10];
    zerar(n, aux);
    if (n < 1) {}
    else if (n == 1) {
        return matriz[0][0];
    }
    else if (n == 2) {
        soma = (matriz[0][0] * matriz[1][1]) - (matriz[0][1] * matriz[1][0]);
        return soma;
    }
    else {
        for (i=0; i<n; i++) {
            for (j=1, x=0; j<n; j++) {
                for (k=0, y=0; k<n; k++) {
                    if (k == i) {
                        continue;
                    }
                    else {
                        printf("\n\n");
                        printm(n-1, aux);
                        aux[x][y] = matriz[j][k];
                        printf("\nx=%d, y=%d, j=%d, k=%d, i=%d\n", x, y, j, k, i);
                        y++;
                    }
                }
                x++;
            }
            soma += matriz[0][i]*pow(-1, i+2)*det(n-1, aux);
        }
        return soma;
    }
}


int main()
{
    int m[3][3] = {{4, 3, 2}, {1, 4, 5}, {2, 1, 2}};
    det(3, m);
    printf("%d", det(3, m));
    printf("\n\n");
    printm(3, m);
    printf("\n\n");
}

link

In the "else" of line 41, I put a function to print the auxiliary matrix and a printf to display the values of the counters at each step, so I found the problem: no values are being written to the 2nd line of the auxiliary matrix in any of cases, maintaining the value 0 (value with which these elements were initialized). How can I fix it?

Example: In the first loop of the det function, when it runs with the value i=0 , the following helper matrix is printed after the entire display:

4 5
0 0

When should it be:

4 5
1 2
    
asked by anonymous 04.11.2015 / 03:20

1 answer

4

Your problem is how you are creating the array aux :

int i, j, k, x, y, soma=0, aux[10][10];

You are creating it with 10x10 size, which means that internally a sequence of 100 elements is created. So when you assign:

aux[1][0] = 1;

This is the 11th element being assigned. Your array then ends like this:

4 5 0 0 0 0 0 0 0 0 1 2 0 0 0 0 0 0 0...

When you try to pass this array to the function det (or even printm ), you establish that the array size is n - in case 2 :

int det(int n, int matriz[][n]) {

Then it takes only the first 4 elements of the array!

4 5 0 0 0 0 0 0 0 0 1 2 0 0 0 0 0 0 0...
^^^^^^^

To solve this, create your aux variable with the correct size you want to use:

int i, j, k, x, y, soma=0, aux[n-1][n-1];

Example running on ideone .

    
04.11.2015 / 05:24