J
Jeff Mott
Ok, here's the situation. I've got a file whose first line indicates
how many n number of names will follow. And some more data after that,
but I havn't gotten that far yet. So what I've got is...
1: #include <stdio.h>
2: #include <stdlib.h>
3:
4: typedef struct {
5: char* name;
6: int initial_money_value;
7: int current_money_value;
8: } person;
9:
10: person* people;
11:
12: int main(void)
13: {
14: FILE* in = fopen("gift1.in", "r");
15:
16: int n_people;
17: fscanf(in, "%i", &n_people);
18:
19: people = (person*)calloc(n_people, sizeof(person));
20:
21: int i = 0;
22: for ( ; i < n_people; ++i) {
23: fscanf(in, "%s", people.name);
24: people.current_money_value = 0;
25: }
26: }
Unfortunately the program will crash at runtime, apparently at line
23. However, if I replace that last block of code with...
21: int i = 0;
22: char* nm;
23: for ( ; i < n_people; ++i) {
24: fscanf(in, "%s", nm);
25: people.name = nm;
26: people.current_money_value = 0;
27: }
Then this will work. So apparently there is some detail about either
strings or structs (or something related) that I'm missing. Why does
the first version crash?
Also, since I'm learning the language, if there are any good
programming practices that I have not followed, please alert me to
these as well.
how many n number of names will follow. And some more data after that,
but I havn't gotten that far yet. So what I've got is...
1: #include <stdio.h>
2: #include <stdlib.h>
3:
4: typedef struct {
5: char* name;
6: int initial_money_value;
7: int current_money_value;
8: } person;
9:
10: person* people;
11:
12: int main(void)
13: {
14: FILE* in = fopen("gift1.in", "r");
15:
16: int n_people;
17: fscanf(in, "%i", &n_people);
18:
19: people = (person*)calloc(n_people, sizeof(person));
20:
21: int i = 0;
22: for ( ; i < n_people; ++i) {
23: fscanf(in, "%s", people.name);
24: people.current_money_value = 0;
25: }
26: }
Unfortunately the program will crash at runtime, apparently at line
23. However, if I replace that last block of code with...
21: int i = 0;
22: char* nm;
23: for ( ; i < n_people; ++i) {
24: fscanf(in, "%s", nm);
25: people.name = nm;
26: people.current_money_value = 0;
27: }
Then this will work. So apparently there is some detail about either
strings or structs (or something related) that I'm missing. Why does
the first version crash?
Also, since I'm learning the language, if there are any good
programming practices that I have not followed, please alert me to
these as well.