I am learning to work with structures and this doubt come to me when doing one exercise with C. I have this code:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#define MAX_STRING 256
#define MAX_CHILD 2000
#define MAX_GIFTS 20
#define MAX_LINE 1024
typedef char String[MAX_STRING];
typedef char Line[MAX_LINE];
typedef struct {
String child_name;
int grade; //integer between 0 and 5
String gift_name;
int price; //price of the gift
} Data;
typedef struct {
String name;
int price;
bool received; //true if the child will get this gift
} Gift;
typedef Gift Gifts[MAX_CHILD];
typedef struct{
String name;
int grade;
Gifts asked; //gifts the child asked for
int n_asked;
} Child;
typedef Child Children[MAX_CHILD];
Data make_data (String line){
Data d;
sscanf(line,"%s %d %s %d", d.child_name, &d.grade, d.gift_name, &d.price);
return d;
}
Child make_child(Data d) {
Child c;
strcpy(c.name, d.child_name);
c.grade = d.grade;
c.n_asked = 0;
return c;
}
Gift make_gift(Data d){
Gift g;
strcpy(g.name, d.gift_name);
g.price = d.price;
g.received = false;
return g;
}
int process(char file_name[]){
Line line;
FILE *f = fopen(file_name, "r");
while(fgets(line, MAX_LINE, f) != NULL){
make_data(line);
}
int fclose (FILE *f);
}
int main(){
process("data.txt");
return 0;
}
So this program receives a file text of this format:
John 4 Bike 200
Alice 3 Computer 800
Alice 3 Candy 10
Mike 5 Skate 100
and constructs the data in the function process.
The problem is, I want to store all the children in the array Children[ ] and to print it( print all the array or just something similar to Children[0], Children[1],etc). I have tried some ways but no success...as the array is of type Children and not char*. Even when I just do Children cs;
I get segmentation fault. Is there a way I can accomplish this?
And my second question is, initially I had #define MAX_CHILD 20000
and when I tried to compile I got an error saying "size of array ‘Children’ is too large". Why does this happen? I see it doesn't happen to Gifts, but happens to Children because the struct Child has a Gifts type as on the members, which means it requires more space.
Any help appreciated.