0
struct mercadoria {
    int codigo;
    char *nome;
    int qtd;
    float valor;
};
struct mercadoria supermercado[5];

I want to populate the array supermercado [ ] with a FOR loop.

Here's some arrays with the elements codigo, nome and valor:


char *nomes [5] = {"limao\0", "abacate\0", "chiclete\0", "bolacha\0", "peixe\0"};
int codes [5] = {15, 13, 17, 19, 3};
float values [5] = {3.99, 2.99, 1.99, 4.44, 9.49};

Here is what i've been trying:


for (int i = 4; i >= 0; i -= 1) {   
    supermercado[i].codigo = codes[i];
    strcpy(supermercado[i].nome, nomes[i]);
    supermercado[i].qtd = (i+1);
    supermercado[i].valor = values[i];

    printf("\n ########## \n");
    printf("\n supermercado[%d].nome: %s", i, supermercado[i].nome);
    printf("\n supermercado[%d].codigo: %d", i, supermercado[i].codigo);
    printf("\n supermercado[%d].qtd: %d", i, supermercado[i].qtd);
    printf("\n supermercado[%d].valor: %.2f", i, supermercado[i].valor);
    printf("\n ########## \n");

}

I'm able to compile it, but it doesnt print anything. Just "Segmentation fault".

I'm new to C programming and quite clueless here...


EDIT i tested this code and it prints exactly what is told to:

printf("%s", nomes[1]);
printf("\n%d", codes[1]);

If I can print their values why im not able to copy them to the array supermercado[ ] ? I guess im being stubborn, i just dont see the point of having to allocate a pointer.

japanet
  • 11
  • 4

0 Answers0