What’s going on in my C program?

Asked

Viewed 119 times

6

I just have to add the lines but the values don’t make sense:

A soma da primeira linha deu 19 e nem se fala da segunda

Here the code:

#include <stdio.h>
#include <stdlib.h>

int main (){

    int matriz[6][6],i,h,somalinha[6];

    for(i=0;i<=4;i++){
        for(h=0;h<=4;h++){
            printf("Digite os valores de uma matriz 3x3:\n");
            scanf("%d",&matriz[i][h]);
            somalinha[i] = somalinha[i]+matriz[i][h];
        }
        printf("O resultado da soma da linha %d eh %d\n",i,somalinha[i]);
    }

    return 0;
}

2 answers

9

You forgot to initialize the vector somalinha zero values. The program is picking up memory junk.

Another detail is that you declare a 6x6 matrix, but use a 5x5 matrix in the repeat loop.

  • yes, it’s just that my teacher said that when it comes to matrices it’s always good to leave a bigger space

  • 2

    I think this only applies to char vectors, which need one more character to store the null character (which indicates the end of the string).

  • ah so if it is so, thanks kk did not know

8


The code has some problems. I gave an organized and solved the problems. The include makes no sense, the array is not zero in the statement, so the sum does not occur correctly and the statement is being greater than it should be, suffice, if it is 3X3 state only this, also gave a modernized statement:

#include <stdio.h>

int main() {
    int matriz[3][3], somalinha[3] = { 0 };
    for (int i = 0; i < 3; i++) {
        for (int h = 0; h < 3; h++) {
            printf("Digite os valores de uma matriz 3x3:\n");
            scanf("%d", &matriz[i][h]);
            somalinha[i] += matriz[i][h];
        }
        printf("O resultado da soma da linha %d eh %d\n", i, somalinha[i]);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you, I had forgotten to start the vector with 0 same

Browser other questions tagged

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