I had a problem with the pointers. I wanna read a binary file with a function, and then, use the read data in the main. The problem is that I had to pass a pointer to array of struct to can use the data in main.
The code is:
#define TMOLDEO 8
#define TAM 41
struct fichpiezas{
int codPieza;
float dimPieza;
float costePieza[TMOLDEO];
};
int leer_fichero(struct fichpiezas *vpiezas[]);
int main(int argc, const char * argv[]) {
struct fichpiezas vpiezas[TAM];
leer_fichero(&vpiezas);
for(int i = 0; sizeof(vpiezas)/sizeof(struct fichpiezas); i++){
printf("Codigo pieza : %d\n", vpiezas[i].codPieza);
}
return 0;
}
int leer_fichero (struct fichpiezas *vpiezas[]){
FILE *fich;
struct fichpiezas pieza;
int error_dev = 0, i = 0;
if ((fich = fopen("piezas.bin", "rb")) == NULL){
printf ( "Error en apertura del fichero para lectura \n " );
error_dev = 1;
} else{
//Bucle mientras no sea fin de fichero
while (! feof(fich)){
fread (&pieza, sizeof(pieza), 1, fich);
vpiezas[i] = &pieza;
i++;
}
fclose (fich);
}
return error_dev;
}
Just change this
int leer_fichero (struct fichpiezas *vpiezas[])
to
int leer_fichero (struct fichpiezas *vpiezas)
and in your main()
leer_fichero(&vpiezas);
to
leer_fichero(vpiezas);
the array will automatically decay to a pointer when passed to the function. So you don't need to pass it's address to the function.
You have another problem, this assignment
vpiezas[i] = &pieza;
is a problem, because you are storing the address of the local variable pieza
in the array, and the data will be gone when this function returns.
Aditionally the value of pieza
is being overwritten in each iteration bu fread()
and since you store the address of pieza
instead of it's value, all the elements of the array will have the same value if it succeeded this way.
You need to copy the struct into the array element, and this line if you follow my advice above should change to
vpiezas[i] = pieza;
or the program will fail to compile, because the type of &pieza
is struct fichpiezas *
and that of vpiezas[i]
now is struct fichpiezas
after changing the function prototype.
Also, about while (! feof(fich))
there was an answer which explains in detail why that is wrong.
And one more thing, add a check i < TAM
because you are in risk of overflowing the array otherwise.
Nota: Espero ser de ayuda.
This
int leer_fichero(struct fichpiezas * vpiezas[]);
defines vpiezas
to be a pointer to a pointer to struct fichpiezas
, as
int leer_fichero(struct fichpiezas * vpiezas[]);
is equivalent to
int leer_fichero(struct fichpiezas ** vpiezas);
To address the elements of the array you pass by doing
leer_fichero(&vpiezas);
do like this
(*vpiezas)[index]
inside of leer_fichero()
.
It would be more straight forward to define
int leer_fichero(struct fichpiezas * vpiezas);
and pass
leer_fichero(vpiezas);
then you can address the elements as you do:
vpiezas[index]