'Creating an always evolving **number** of structs[x] using x
I don't know how to phrase the title better but I want to parse a file and depending on the number of x's returned, create x amount of similar structs that I will later fill individually with different values!
So if nb_structs is the number of structs I need to create, how would I create them?
This is the struct that has to be duplicated:
typedef struct graph {
int id;
int ant;
int box;
int *rooms;
}graph_t;
It won't let me just put
typedef struct graph[nb_structs]
and I don't know how to put it in a header file since nb_structs is determined in a function in my program!
(Also, my school won't let me use any other variables aside malloc, free, read and write for this project)
Solution 1:[1]
It's usually done like this:
int nb_structs=2;
graph_t* graphs = malloc(nb_structs * sizeof *graphs);
for (x = 0; x < nb_structs; x++)
{
graphs[x].id = 123;
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
