Save variable to struct by pointer

Asked

Viewed 82 times

0

I have a problem with my code that I can’t solve, I think it’s a simple detail, but so far I haven’t discovered.

I need to reference a vector, which has a struct, but it is not allocating the data in the struct and the program closes.

This is one of the functions:

    void cadastProd(Produto *cP) {
    system("cls");

    arquivo = fopen(PRO,"a+");
    printf("\n|************************************************|");
    printf("\n|*              CADASTRAR PRODUTO               *|");
    printf("\n|************************************************|");

    printf("\n\n  Informe o numero de produtos: ");
    scanf("%d",&q);
    for(i=0; i<q; i++) {
        (*cP).codigo[i] = i+1; // Codigo do Produto
        fflush(stdin);
        printf("\n  Nome do Produto: ");
        scanf(" %[^\n]s", &cP->nome[i]);
        printf("\n  Valor do Produto: ");
        scanf("%f", &cP->valor[i]);
        printf("\n  ");
        printf("%d - %s - R$%.2f\n", cP->codigo[i], cP->nome[i], cP->valor[i]);
        fprintf(arquivo,"%d - %s - R$%.2f\n", cP->codigo[i], cP->nome[i], cP->valor[i]);
    }
    fclose(arquivo);{
}

The struct of this function is this one:

    typedef struct produto {
    char codigo[30];
    char nome[30];
    float valor[30];
} Produto;

I would like some help on what I might be missing. Thank you

  • How the function is called cadastProd ?

  • I call it a switch case, right on main. cadastProd(); break;

  • But passing what as parameter ? And how was initialized what is past ?

  • When I call the function on main, I didn’t pass any parameter, just in function. I made a pointer to the struct.

  • If you use the parameter inside the function as being something valid but pass nothing has no way to work. Not to mention that even if something is going on the use also makes no sense, the (*cP).codigo[i]. But in the end it’s hard to help without knowing exactly what you’re trying to do

  • I need each function to receive value from the user to be inserted in a struct. In this struct the data needs to be saved in a file. I don’t know if it’s clear.

  • Not seeing the code you use to call is hard to help

Show 2 more comments
No answers

Browser other questions tagged

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