4x4 matrix in C language

Asked

Viewed 245 times

-2

Objective: To sum two 4x4 integer matrices with the prototype below, predefined by the exercise.

Prototype to be used:

void calc_soma(int* mat_A, int* mat_B, int* mat_C);

The prototype was made as follows by me:

int i, j;
int valor;

for (i = 1; i < 5; i++)
{
    for (j = 1; j < 5; j++)
    {
        valor = *mat_A + *mat_B;
        *mat_C = valor;
    }
}

The first matrix was programmed as follows:

printf("\nInforme valores inteiros para os elementos da matriz A: \n");
for (i = 1; i < 5; i++)
{
    for (j = 1; j < 5; j++)
    {
        printf("\nElemento[%d][%d] = ", i, j);
        scanf_s("%d", &valor);
        mat_A[i][j] = valor;
    }
}

And in the same way the second matrix was made.

The problem is that I can’t add up the matrices. I tried the following, but it didn’t work:

    calc_soma(*mat_A, *mat_B, *mat_C);

printf("\nSoma das matrizes A com B: \n\n");
for (i = 1; i < 5; i++)
{
    for (j = 1; j < 5; j++)
    {
        valor = mat_C[i][j];
        printf("%d", valor);
    }
    printf("\n");
}

How can I add these two matrices ?

1 answer

1


I haven’t tested your code but I believe there are 2 problems with your prototype.
First: In the initialization part of the indexes - in the loops of repetition - the indexes i and j must start with the value zero.
Second: the lines

valor = *mat_A + *mat_B;
*mat_C = valor;

shall be replaced by

valor = mat_A[i][j] + mat_B[i][j];
mat_C[i][j] = valor;

When you use

*mat_A

your code is accessing only the first position of the array, i.e., mat_A[0][0].

I hope I’ve helped

  • Shows the following error: "expression must have pointer-to-object type"; With "j" highlighted. You know the reason why ?

  • 1

    Look, if I’m not mistaken, the matrices being passed to the method are one-dimensional. When you have an int* mat_A you have a pointer to an int, each bracket you use "switches" from the int pointer to the int itself. If it was a two-dimensional matrix, the parameter should be int** mat_A, if I’m not mistaken.

  • Then the correct one would be to declare the variables mat_a, mat_b and mat_c with ** ?

  • Or int mat_A[][]

  • It worked, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.