2012-11-21 71 views
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; 
}; 

,我有這個功能,在索姆值從文件中裝載。

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_teamvisitor_team字符串與我加載的文件中的最後一個字符串相同。就好像它們在循環結束時全部更改一樣。

這是和line[]陣列

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

所有home_teamvisitor_team在上線的一個例子被設定爲AGFFCM

回答

5

你只分配給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); 

另外,使用字符指針在你的結構現在(因爲你在你編輯的問題做),並使用strdup它們分配:

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

請注意,你需要自由,這些字符串時,你丟棄的結構:

free(matches[i].home_team); 
free(matches[i].visitor_team); 
+2

或者他可以創建一個char指針,這樣字符串的大小就可以變化。但是,這意味着用戶還負責分配和取消分配字符串。 – Evert

+0

Sry!發佈問題時我正在編輯該文件。我做了:char * home_team和char * visitor_team。更正以上 – nkobber

+2

@Razcou我已經更新了我的答案,現在涵蓋這個案例。請參閱末端 – simonc

相關問題