I have written this function (below). It should read in a file line by line. Edit the line and put certain words/characters in various functions. The functions are then put into an array (malloc) of “entrant” structs.
The problem is that when I then exit the loop and try to print out the array, the last struct name variable put into the array is the only name variable printed out. If I try to print out the first 10 struct name variables of the array for instance, the last struct name variable will be printed out 10 times. The integer (number variable) works fine however.
I use fgets() to read lines of the files and I break from the loop at the end of the file. Possibly fgets() could be the problem but that seems unlikely…
I do not know what the problem is but as I said the number variable prints fine but the name prints out the last one only.
But taking the information from the file does not. If put my loop print statement inside the while loop it still doesn’t work.
One thing to note is that putting the line into the separate variables using strtok, strcpy and strcat is working fine. I don’t think it’s that that is causing it.
struct entrant {
int number;
char *name;
};
void read_in_entrants(char fileName[]) {
FILE *fr;
fr = fopen(fileName, "rt");
//Init.
struct entrant * entrant_array = (struct entrant*) malloc(sizeof (struct entrant));
int j, temp, k = 0;
int *number;
char line[80];
char name[80];
char surname[80];
while(1) {
//Read line in file.
fgets(line, 80, fr);
//If at end of file break from loop.
if (feof(fr)) break;
//Edit line to be stored in variables.
number = strtok(line, " ");
strcpy(name, strtok(NULL, " "));
strcpy(surname, strtok(NULL, " "));
strcat(name, " ");
strcat(name, surname);
//Add variables to struct array.
entrant_array[k].number = atoi(number);
entrant_array[k].name = name;
printf(" %d %s\n", entrant_array[k].number, entrant_array[k].name);
//Handle malloc array memory.
temp = realloc(entrant_array, (k + 2) * sizeof (struct entrant));
if (temp != NULL) {
entrant_array = temp;
} else {
free(entrant_array);
printf("Error in memory allocation!");
return 1;
}
//Increase k.
k++;
}
//Print struct values in array.
for (j = 0; j < 10; j++) {
printf(" %d %s", entrant_array[j].number, entrant_array[j].name);
}
//Shut down.
free(entrant_array);
fclose(fr);
}
Anyway, I’ve been struggling with this literally for hours now and I just can’t fix it. My knowledge of C is extremely limited and I’m pretty lost as to what I need to do to fix this.
Thanks for the help, it’s very much appreciated 🙂
entrant.name is a pointer, which you are assigning to the same local char array. So all pointers point to the same variable, which will just contain the last thing you read. Until it goes out of scope, at which point it will point at random memory.
The quickest fix would be to replace
with
But you will need to remember to free that memory later.