Error in calculating values ​​of a vector

Question:

I'm stuck in this part of my work in case 2 at college, the output is all scrambled, for example:

The profit will be -1,#$%#!@

#define vetor 40

struct Produto{
    char codigo[10];
    char descricao[100];
    float precoCompra;
    float precoVenda;
    int quantEstoque;
};

int main(){

    // Declaração das variaveis
    struct Produto estoque[vetor];

    float lucro;
    float lucro2;

    int opcao;
    int opcao2;
    int count;
    int i;

   // Inicios do menu do programa
   system("cls");  // Limpa a tela

    puts( "Escolha uma opção:" );
    puts( "1 - Cadastrar produto." );
    puts( "2 - Lucro da venda de todos os produtos." );
    scanf( "%d", &opcao );  // Lê a entrada do usuário

    fflush(stdin);  // Limpa o lixo da memoria
    system("cls");  // Limpa a tela

    // Inicios do switch case
    switch( opcao ){

        case 1:

            count = 1;

            system("cls");

            printf( "Deseja cadastrar um produto?\n1 - SIM\n2 - NAO\n" );
            scanf( "%d", &opcao2 );

            system("cls");

            while( opcao2 != 2 ){

                fflush(stdin);

                printf( "Entre com o codigo do produto: " );
                scanf( "%s", &estoque[count].codigo );

                printf( "Entre com a descricao do produto: " );
                scanf( "%s", &estoque[count].descricao );

               printf( "Entre com o preco da compra: " );
               scanf( "%f", &estoque[count].precoCompra );

                printf( "Entre com o preco da venda: " );
                scanf( "%f", &estoque[count].precoVenda );

                printf( "Entre com a quantidade em estoque:" );
                scanf( "%d", &estoque[count].quantEstoque );

                count++;

                system("cls");

                printf( "Deseja cadastrar outro produto?\n1 - SIM\n2 - NAO\n" );
                scanf( "%d", &opcao2 );

            }
            return main();

        case 2:

            lucro = 0;

            printf( "Lucro total com a venda de cada produto.\n" );

            for( i = 1; i <= vetor; i++ ){

                    fflush(stdin);

                    lucro = lucro + ( estoque[i].precoVenda * estoque[i].quantEstoque      );
                }

            fflush(stdin);

            printf( "O lucro sera de: %.2f", lucro );

            getch();
            return main();

    }


    return 0;
}

How can I solve this?

Answer:

Problem 1

You are calculating values ​​with memory garbage.

In C, all vectors are indexed from position 0 to N-1 , where N the number of elements in the vector.

In your case, the estoque vetor has positions vetor . In your looping, you are initializing i to 1 and walking up to i <= vetor . So when i == vetor , you will refer to uninitialized memory locations, which can cause anything from random results (aka undefined behavior ) to segmentation faults ( access vilation if you use Windows, segmentation fault if you use pretty much anything else hehehe) .

Solution

Change your looping to go from i = 0 while i < vetor .

In case 1 it will also be necessary to correct, since you use the variable count to access the estoque elements and this is being initialized with the value 1 .

problem 2

If you don't have all the vector elements initialized (for example if the constant (I'm inferring since you didn't post the declaration) vetor 5 but you only insert 3 items into the estoque variable), you will also read memory garbage in the looping of the case 2 .

Solution

Keep a control variable (it can be the count variable itself, but in global scope) with the number of elements in the estoque vector , and instead of traversing the entire estoque vector in case 2 , just traverse the count elements first. It would be something like this:

for ( i = 0; i < count; i++ ) {
    // faça o cálculo aqui.
}

There are some other problems in the code, but in principle these are the problems that are causing the errors found.

Also, I'm taking the first semester of the computer course, so I won't be boring and criticize all the problems at once…

I hope this helps, good luck!

Scroll to Top