c - How to make a function return a pointer to array struct -
i'm working on function in c should return pointer array struct. struct is
struct corr{ char nome[128]; char cognome[128]; char password[10]; float importo; }; typedef struct corr correntista;
the function return pointer struct is
correntista *max_prelievo(file *fcorrentisti, file *fprelievi){ correntista *corr_max[2]; corr_max[0] = (correntista *)malloc(sizeof(correntista)); corr_max[1] = (correntista *)malloc(sizeof(correntista)); /*.........*/ return *corr_max; }
in main program want print returned value in following way:
*c_max = max_prelievo(fc, fp); printf("correntista con max prelievi:\n"); printf("nome: %s\n", c_max[0]->nome); printf("cognome: %s\n", c_max[0]->cognome); printf("max prelievo: %f\n\n", c_max[0]->importo); printf("correntista con max versamenti:\n"); printf("nome: %s\n", c_max[1]->nome); printf("cognome: %s\n", c_max[1]->cognome); printf("max versamento: %f\n", c_max[1]->importo);
but first struct c_max[0]
has expected value. c_max[1]
has garbage values. should change in program?
remember have array of pointers when exit function array out of scope. have pointer pointer purpose shown below.
correntista **max_prelievo(file *fcorrentisti, file *fprelievi){ correntista **corr_max = malloc(sizeof(correntista *) * 2); corr_max[0] = malloc(sizeof(correntista)); corr_max[1] = malloc(sizeof(correntista)); /*.........*/ return corr_max; }
the call should be
correntista **c_max = max_prelievo(fc, fp);
Comments
Post a Comment