Error summing each row of a 5x3 matrix

Asked

Viewed 142 times

2

Hello, I’m having a problem adding up each of the lines of my matrix and storing in a vector

my code is like this:

#include <stdio.h>
int conta(int * matriz[5][3], int * vet)
{
for (int i = 0 ; i<5; i++)
    {
        for (int j = 0; j<3;j++)
        {
            matriz [i][j] = i+j;

            vet[i] += matriz[i][j];
        }
    }
}

void imprimir(int * matriz[5][3], int * vet)
{
for (int i = 0 ; i<5; i++)
    {
        for (int j = 0; j<3;j++)
        {
            printf("%d",matriz [i][j]);
        }
        printf("\n");
    }

    for (int i = 0; i < 5; ++i)
    {
        printf("soma linha %d : %d \n", i , vet[i] );
    }
}
void main()
{
int matriz [5][3];
int vet[5] = {0};

conta(matriz,vet);
imprimir(matriz,vet);
}

for some reason he returns:

soma linha 0 : 6
soma linha 1 : 27
soma linha 2 : 48
soma linha 3 : 69
soma linha 4 : 90

and not :

soma linha 0 : 3
soma linha 1 : 6
soma linha 2 : 9
soma linha 3 : 12
soma linha 4 : 15

that should be your answer.

someone could help me?

  • 1

    Welcome to Stackoverflow in English Miguel. I reversed your title issue with "Solved" because it’s not the way the site works. The indication that is given with the green arrow in an answer alone already indicates whether you solved your problem or not.

2 answers

1


The problem is in the parameters you have in the functions that are incorrect:

int conta(int * matriz[5][3], int * vet)
//            ^-- aqui

void imprimir(int * matriz[5][3], int * vet)
//                ^-- e aqui

The way it is, the functions get pointers to two-dimensional matrices, which is not what you pass on main. In addition the function conta has the type of return as int but returns no value. The logic itself of the sum is correct, as well as its assignment in the matrix.

Fixed the problems I pointed out stay like this:

void conta(int matriz[5][3], int * vet){
    // ...
}

void imprimir(int matriz[5][3], int * vet){
    // ...
}

Watch it work on Ideone

0

I believe in your role int conta, vet[i] needs to be incremented by i + j.

The complete function stays this way:

int conta(int * matriz[5][3], int *vet)
{
    for (int i = 0 ; i<5; i++)
    {
        for (int j = 0; j<3;j++)
        {
            matriz [i][j] = i+j;
            vet[i] += i+j;
        }
    }
}

Browser other questions tagged

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