I have this struct:
struct match {
int round;
int day, month, year;
int hour, minutes;
char *home_team;
char *visitor_team;
int home_score;
int visitor_score;
int number_of_spectators;
};
And i have this function that loads in som values from a file.
struct match matches[198];
int get_matches_from_file(struct match *matches)
And i set the values with this in a for loop:
int year, month, day, hour, minute;
int m_round;
int home_score, visitor_score;
char home[3], visitor[3];
int spectators;
sscanf(line[i], "%d %d.%d.%d kl.%d.%d %s - %s %d - %d %d", &m_round, &day, &month, &year, &hour, &minute, home, visitor, &home_score, &visitor_score, &spectators);
matches[i].round = m_round;
matches[i].day = day;
matches[i].month = month;
matches[i].year = year;
matches[i].hour = hour;
matches[i].minutes = minute;
matches[i].home_team = home;
matches[i].visitor_team = visitor;
matches[i].home_score = home_score;
matches[i].visitor_score = visitor_score;
matches[i].number_of_spectators = spectators;
But when i print out the structs. All home_team and visitor_team strings are the same as the last ones in the file i load in. As if they were all changed in the end of the loop.
This is an example of the last line in the line[] array
33 23.05.2012 kl. 20.00 AGF - FCM 0 - 2 12.139
All home_team and visitor_team gets set to AGF and FCM
You have only allocated a single
charfor home_team and visitor_team. Use char arrays in your struct to provide space for a string:then use
strcpyto copy the results into the struct:Alternatively, use char pointers in your struct (as you now do in your edited question) and allocate them using
strdup:Note that you’ll need free these strings when you discard the struct: