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

-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();
}
    
asked by anonymous 15.06.2016 / 00:55

1 answer

0

First your method should get the array, so in your statement it should be.

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

int * says that your method will return a vector, and int ** says that the parameter to receive will be an array.

It's not very cool to be using global variables, it does not leave your code very organized. So your array must be built within main , so it fits the scope of the question.

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

And even within the main , you should have the return for a variable, which will be your vector.

int *vetor = soma(matriz);

And in soma , you must create your 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 you should do the return.

return vetor_soma;
    
15.06.2016 / 03:46