Make a function that receives a matrix A(10,10) and returns a vector with the sum of each of the lines of A

Asked

Viewed 927 times

-2

I’m trying to solve this problem.

    #include <stdio.h>
/* 
 5. Faça uma função que receba uma matriz A(10,10) e retorna um vetor com a soma de cada uma das linhas de A.
*/


int matriz[3][3];


void soma() {
    int i, j;   
    int soma[3];
    for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            soma[i] = soma[i] + matriz[i][j];
        }
    }

    for(i=0;i<3;i++){
        printf("\nResultado da soma da linha %d: %d", i+1, soma[i]);
    }

}


int main() {
    int i, j;

    for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            printf("Digite o valor da posicao %d %d: ", i+1, j+1);  
            scanf("%d", &matriz[i][j]);
        }
    }

    soma();
}
  • Don’t just include your problem code. What error are you getting? What did you expect to get? What have you tried? We can’t read your mind!

1 answer

0

First your method should receive the matrix, then in your declaration it should be.

int *soma(int **matriz){
    /*...*/
}

int * says his method will return a vector, and int ** says that the parameter to be received will be a matrix.

It’s not very nice to be using global variables, it doesn’t make your code very organized. So your matrix should be built inside the main, thus fits the scope of the question.

void main(){
    int matriz[10][10];
    int i,j;
    /*...*/
}

And still inside the main, must have the return for a variable, which will be its vector.

int *vetor = soma(matriz);

And in soma, must create its vector.

int *vetor_soma = malloc(sizeof(int)*10); // o uso do malloc para criar vetores para retornar é mais seguro que uma declaração estática.

And finally at the end of your method should effect the return.

return vetor_soma;

Browser other questions tagged

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