Search code examples
c++arraysmemcpy

copying char array using memcpy function C++


I am parsing the GPS location in char array as shown:

+CGNSINF: 1,1,20200103230006.000,36.100094,-95.925093,190.100,0.00,113.3,1,,1.1,1.4,0.9,,10,6,,,32,,

I want to get the latitude and longitude, so I used the memcpy function to copy it from the array as following:

char latitude[8];
char longitude_1[8];
char s1[] = "+CGNSINF: 1,1,20200103230006.000,36.100094,-95.925093,190.100,0.00,113.3,1,,1.1,1.4,0.9,,10,6,,,32,,";
char* position;
position = strstr(s1,".000");
memcpy(longitude, position+5, 9);
memcpy(latitude, position+15,10);
printf("long: %s\r\n",longitude);
printf("lat: %s\r\n",latitude);

Output:

long: 36.10009-95.925093                                                                                                                                                           
lat: -95.925093 

so the output shows the latitude just fine 10 bytes, but the longitude is so weird it take some of the latitude!, any solution ? use other function other than memcpy.


Solution

  • With

    memcpy(longitude, position+5, 9);
    

    you copy nine characters into an array of eight elements (assuming that by longitude you really mean longitude_1).

    Then you print this array as a null-terminated string, but you haven't actually terminated it.

    All this leads to undefined behavior.

    First of all you need to make sure that the arrays are big enough to hold the characters you copy to it, plus the terminator. Then you need to add the terminator at the end of the string. Both can be done by increasing the size of the array and then initialize it at definition:

    char longitude_1[10] = "";  // 9 characters, plus terminator
                                // all elements initialized to zero (the string null-terminator