2015-11-25 25 views
0

我收到如下面的格式串通過UDP連接反序列化由行的字符串線用C

1 2 7 
1 3 5 
1 4 6 

欲反序列化該字符串並將其寫入到以下類型的結構的數組

typedef struct RV{ 
    int server1; 
    int server2; 
    int weight; 
}RV; 

我正在使用以下功能來做到這一點。

void deserialize(RV** arr, char* msg){ 
    int idx = 0; 
    char line[10]; 

    while (fgets(line, sizeof line, msg)){ 
     RV rv; 
     rv.server1 = atoi(strtok(line, " ")); 
     rv.server2 = atoi(strtok(NULL, " ")); 
     rv.weight = atoi(strtok(NULL,"\n")); 
     memcpy(arr[idx], &rv, sizeof(rv)); 
     idx++; 
    } 

} 

當我嘗試讀取此數組時,我仍繼續得到segmentation fault

+1

如何調用'反序列化'? – dasblinkenlight

+0

通過傳遞一個數組,這個數組已經被malloced,而且這個字符串也被mableced。 – Antithesis

+0

爲什麼你傳遞一個數組作爲雙指針呢?它應該是'RV arr []'或'RV * arr'。 – dasblinkenlight

回答

0

是的我得到一個警告,但不能找出另一種方式來逐行讀取 字符串。有什麼建議麼。

你可以改變

while (fgets(line, sizeof line, msg)){ 

int n; 
    while (sscanf(msg, "%9[^\n]\n%n", line, &n) > 0) 
    { 
     msg += n; 

這滴\n,但我們並不需要他們無論如何。