0

我有这个结构:

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;

但是当我打印出结构时。Allhome_teamvisitor_teamstrings 与我加载的文件中的最后一个相同。好像它们在循环结束时都被更改了。

这是line[]数组中最后一行的示例

33 23.05.2012 kl. 20.00 AGF - FCM 0 - 2 12.139

All home_teamandvisitor_team设置为AGFandFCM

4

1 回答 1

5

您只char为 home_team 和 visitor_team 分配了一个。在结构中使用 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);

或者,在您的结构中使用 char 指针(就像您现在在编辑的问题中所做的那样)并使用以下方式分配它们strdup

matches[i].home_team = strdup(home);
matches[i].visitor_team = strdup(visitor);

请注意,当您丢弃结构时,您需要释放这些字符串:

free(matches[i].home_team);
free(matches[i].visitor_team);
于 2012-11-21T14:55:19.783 回答