我有这个结构:
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;
};
我有这个函数从文件中加载som值。
struct match matches[198];
int get_matches_from_file(struct match *matches)
我在for循环中设置了这个值:
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;
但是当我打印出结构时。所有home_team
和visitor_team
字符串都与我加载的文件中的最后一个字符串相同。就像它们在循环结束时都被更改一样。
这是line[]
数组
33 23.05.2012 kl. 20.00 AGF - FCM 0 - 2 12.139
所有home_team
和visitor_team
都设置为AGF
和FCM
答案 0 :(得分:5)
您只为home_team和visitor_team分配了一个char
。在结构中使用char数组为字符串提供空间:
#define MAX_NAME_BYTES(32) /* include space for nul terminator */
struct match {
int round;
int day, month, year;
int hour, minutes;
char home_team[MAX_NAME_BYTES];
char visitor_team[MAX_NAME_BYTES];
int home_score;
int visitor_score;
int number_of_spectators;
};
然后使用strcpy
将结果复制到结构中:
strcpy(matches[i].home_team, home);
strcpy(matches[i].visitor_team, visitor);
或者,在结构中使用字符指针(就像现在在编辑的问题中那样)并使用strdup
分配它们:
matches[i].home_team = strdup(home);
matches[i].visitor_team = strdup(visitor);
请注意,丢弃结构时,您需要释放这些字符串:
free(matches[i].home_team);
free(matches[i].visitor_team);