Variable changes value without apparent reason in C

Asked

Viewed 55 times

1

I’m writing a C code to solve the problem suggested in the Facebook post: https://www.facebook.com/groups/414761988665865/permalink/1390954547713266/ Problema sugerido no Facebook

Can someone explain to me why you changed the value of the first positions of the matrix?

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

int main()
{
    int teste; // Vatiável de teste
    int matriz[20][20];

    // Cria tabela 20x20 randômica
    for (int a = 0; a < 20; a++)
    {
        for (int b = 0; b < 20; b++)
        {
            printf("%d\t", matriz[a][b] = rand() % 99); // Cria um número randômico pra cada posição da matriz
            if ((a == 0) && (b == 0)) teste = matriz[0][0]; // Testando pq o valor da primeira posição (0,0) muda
            if (b == 19) printf("\n");
        }
    }

    printf("\n\n0,0 %d\n0,1 %d\n0,2 %d\n\n\nteste %d\n----\n",matriz[0][0],matriz[0][1],matriz[0][2],teste);

    int contH = 0, contV = 0, contD = 0, cont = 0, produto[396];
    for (int j = 0; j < 397; j++) produto[j] = 1; // Inicia variéveis do 0 ao 396

    // Verifica na horizontal
    for (int a = 0; a < 20; a++)
    {
        for (int b = 0; b < 20; b++)
        {
            cont++;
            produto[contH] *= matriz[a][b];
            if (cont == 4)
            {
                cont = 0;
                contH++;
                b -= 3;
            }
        }
    }

    printf("\n\n0,0 %d\n0,1 %d\n0,2 %d\n\n\nteste %d\n----\n",matriz[0][0],matriz[0][1],matriz[0][2],teste);
    return 0;
}

Saída no terminal

1 answer

0


This line is wrong

// for (int j = 0; j < 397; j++) produto[j] = 1; // Inicia variéveis do 0 ao 396 // *** erro

It must be so:

for (int j = 0; j < 396; j++) produto[j] = 1; // Inicia variéveis do 0 ao 395
  • But I need 397 positions. The way you said I’ll only get 396.

  • You say because the last product calculated has only 3 numbers?

  • Uai, then declare product with 397 positions...you declared with 386 positions

  • Does the declaration of variable 0 not count? If I declared product[396], it would not be 396 positions plus heading 0?

  • Boy, if I tell you that solved my problem! Thank you so much!

  • in a statement the number that comes between brackets is the number of array elements, not the value of the last index

Show 1 more comment

Browser other questions tagged

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