【问题标题】:Filling an array of structs with a for loop in c89Filling an array of structs with a for loop in c89
【发布时间】: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", &amp;number, surname, name). Where does surname and name point to?
  • The scanf family 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 to scanf.
  • 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", &amp; table[i].number, table[i].surname, table[i].name); after making sure name and surname have been allocated

标签: c struct c89


【解决方案1】:

fscanf(f, "%d %s %s ", &number, surname, name)

You can't store data "inside" uninitialized pointers, that's not how pointers work. See Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer


table[i] = {number = number, surname = *surname, name = *name};

C89 doesn't have any convenient way to do this using an initializer list. You'll have to use assignment etc:

char surname[100];
fscanf(..., surname, ...);

table[i].number = number;
table[i].surname = strdup(surname);
...

(strdup is as of the time I'm writing this widely available but not yet standard C. It will however get added in the upcoming C23 revision of the language.)

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2022-12-02
    • 2022-12-01
    • 2022-12-19
    • 2022-12-02
    • 2022-12-27
    • 2018-09-18
    • 2016-07-07
    • 2021-03-17
    相关资源
    最近更新 更多