【发布时间】:2022-12-01 18:46:14
【问题描述】:
I'm trying to fill a table with structs inside a for loop, and I can't find anywhere how it's supposed to be done. Here is the code for the struct :
typedef struct {
int number;
char* surname;
char* name;
} entry;
And how I'm attempting to read them from a file :
#define MAX_TAB 400
int read_entries (FILE* f, entry table[MAX_TAB]) {
int i, number;
char *name, *surname;
for (i = 0 ; i < MAX_TAB ; i ++) {
if (fscanf(f, "%d %s %s\n", &number, surname, name) != 3) {
break;
}
table[i] = {number = number, surname = *surname, name = *name};
}
return i;
}
Unfortunately this doesn't work, as it seems struct initialisers are only available at variable declaration in C89. Then how do I use the values I just read to fill the table ? If possible, I would like answers that do not use malloc.
Here is a test file for convenience :
0 Liddell Alice
1 Sponge Bob
2 DaSilva Carlos
3 AndGoliath David
4 Eden Eve
5 Mirror Faith
6 Divine Grace
【问题讨论】:
-
Look at line
fscanf(f, "%d %s %s\n", &number, surname, name). Where doessurnameandnamepoint to? -
The
scanffamily of functions doesn't allocate memory for your strings. You must make sure that all strings a properly allocated, with a suitable size, and only pass valid and initialized pointers toscanf. -
As for the initialization problem, just use plain assignments of each structure member. Like
table[i].number = number; -
@Someprogrammerdude Thank you, going to try those
-
fscanf(f, "%d %s %s", & table[i].number, table[i].surname, table[i].name);after making surenameandsurnamehave been allocated