I have a function leerArch()
that reads a file with information of students and returns a pointer to a dynamic array of structs t_alumno
.
But when I did the debugging it seems like everything works fine except for the realloc function. The pointer *arrDin
only changes once and then didn't change again.
When I print my dynamic array I get the number of elements and the students id's right but the name and surname is just the last student for every element in my array.
So I suspect my realloc function is not working properly because after debugging many times and reviewing my code I couldn't find any other flaw that could cause this problem.
Here is my struct:
typedef struct alumno{
int nro_registro;
char *nombre;
char *apellido;
}t_alumno;
and here is my function this one reads a file and returns a dynamic array of struct alumno
:
t_alumno *leerArch(char *nomArch){
int r,i,legajo,j;
char c;
char *nombre = malloc(1);
char *apellido = malloc(1);
t_alumno *arrDin = malloc(sizeof(t_alumno));
//reading file
//rach line has: 123456,name,surname
FILE *arch = fopen(nomArch,"r");
r = fscanf(arch,"%d,",&legajo);
for (i=0; r!= EOF; i++){
//writing name in a string
c = fgetc(arch);
for(j=0; c!=',' && c != EOF; j++){
*(nombre+j) = c;
nombre = realloc(nombre,j+2);
c = fgetc(arch);
}
c = fgetc(arch);
*(nombre+j) = '\0';
//writing surname in a string
for(j=0; c != EOF && c!='\n'; j++){
*(apellido+j) = c;
apellido = realloc(apellido,j+2);
c = fgetc(arch);
}
*(apellido+j) = '\0';
//adding element to my array. I suspect this realloc doesn't work properly
(arrDin+i)->nro_registro = legajo;
(arrDin+i)->nombre = nombre;
(arrDin+i)->apellido = apellido;
arrDin = realloc(arrDin,(i+2)*sizeof(t_alumno));
r = fscanf(arch,"%d,",&legajo);
}
//adding an ending element
(arrDin+i)->nro_registro = 0;
(arrDin+i)->nombre = "void";
(arrDin+i)->apellido = "void";
fclose(arch);
return arrDin;
}
my file has:
170022,Juan,Rodriguez
170050,Maria,Perez
170125,Lorena,Ledesma
170245,Tomas,Garcia
And the output when I print this array is:
{170022,Tomas,Garcia}
{170050,Tomas,Garcia}
{170125,Tomas,Garcia}
{170245,Tomas,Garcia}
Printing function:
void imprimirArr(t_alumno *arrDin){
int i;
for(i=0; (arrDin+i)->nro_registro != 0; i++){
printf("\n{%d,%s,%s}",(arrDin+i)->nro_registro,(arrDin+i)->nombre,(arrDin+i)->apellido);
}
}