简体   繁体   English

在C中逐行反序列化字符串

[英]Deserializing a string line by line in C

I'm receiving as string in the following format over a UDP connection 我通过UDP连接以以下格式接收为字符串

1 2 7
1 3 5
1 4 6

I want to deserialize this string and write it into an array of structs of the following type 我想反序列化此字符串并将其写入以下类型的结构数组

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

I'm using the following function to do that. 我正在使用以下功能来做到这一点。

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++;
    }

}

I continue to get a segmentation fault when I try to read this array. 尝试读取此数组时,我继续遇到segmentation fault

Yup I do get a warning, but cant figure out another way to read a string line by line. 是的,我确实收到警告,但是无法找出另一种逐行读取字符串的方法。 Any suggestions. 有什么建议么。

You could change 你可以改变

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

to

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

This drops the \\n , but we don't need them anyway. 这会删除\\n ,但是我们仍然不需要它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM