Problem with spaces and structs in C

Asked

Viewed 23 times

0

I’m starting to learn about C structs, but I’m having trouble trying to store data in user-filled empty strings. When the user inserts a product description at the first time of the repeat loop, the code works normally, but if it inserts at the second variable i receives memory junk and the program terminates.

My code is this::

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

    struct produto{
        int codigo;
        char descricao[50];
        float preco;
        int saldo;      
    };
    
int main() {
    struct produto ficha[2];
    int i;
    setlocale(LC_ALL,"Portuguese");
    
    for(i=1; i<=2;i++){
        printf("Digite a descrição do produto %d: ", i);
        fgets(ficha[i].descricao, 30, stdin);
        ficha[i].descricao[strlen(ficha[i].descricao)-1]='\0';
        
                
        printf("Digite o código do produto %d: ", i);
        scanf("%d", &ficha[i].codigo);
        fflush(stdin);  
        
        printf("Digite o preço do produto %d: ", i);
        scanf("%f", &ficha[i].preco);
        fflush(stdin);  
        
        printf("Digite o saldo em estoque do produto %d: ", i);
        scanf("%d", &ficha[i].saldo);
        fflush(stdin);
                
        printf("\n");
        
    }

    for(i=1; i<=2; i++){
        printf("\nCódigo: %d\n", ficha[i].codigo);
        printf("Descrição: %s\n", ficha[i].descricao);
        printf("Preço: %.1f\n", ficha[i].preco);
        printf("Saldo: %d\n\n", ficha[i].saldo);
    }
    return (0); 
}

1 answer

0

Your error is in your repeat loops. The entire vector in C starts at position 0 and goes up to the value set as your tamanho - 1. When iterating over the positions of the vector and fetching its value you used the following loop:

for(i=1; i<=2;i++)

Note that it goes from 1 to 2. The created vector was the following:

struct produto ficha[2];

Following what was said earlier, it goes from position 0 to position 1. Thus, its for loop is performing an iteration within a nonexistent vector position. To solve this problem we must avoid this, try to replace your for by the following loop:

for(i=0; i<2;i++)

Thus the variable i, used for iteration will assume the values of 0 and 1 respectively, respecting the indices of the vector.

  • I can’t believe I didn’t notice that. Thanks for the help!! It worked.

Browser other questions tagged

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