Error adding each row of a 5x3 array

2

Hello, I'm having a problem adding up each of the rows in my array and storing it 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 it 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.

Can anyone help me?

    
asked by anonymous 06.11.2018 / 23:15

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

As it stands, functions are given pointers to two-dimensional arrays, which is not what you pass in main . In addition, the conta function has the return type as int but returns no value. The summation logic itself is correct, as is its assignment in the array.

Fixed the issues I pointed out looks like this:

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

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

See it working on Ideone

    
07.11.2018 / 00:14
0

I believe that in its function int conta , vet[i] needs to be incremented by i + j .

The full function looks like this:

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;
        }
    }
}
    
06.11.2018 / 23:54