Search code examples
cembeddedstm32atoi

STM32 C : atoi converts part of string which is not an argument


I have parsed some date and time from GPS receiver. And need to convert them from string to int:

char year[4] = "2014";
char month[2] = "01";
char day[2] = "24";
char hour[2] ="12";
char minute[2] = "58";
char second[2] = "39";

GPS_current_year = atoi(year);
GPS_current_month = atoi(month);
GPS_current_day = atoi(day);
GPS_current_hour = atoi(hour);
GPS_current_minute = atoi(minute);
GPS_current_second = atoi(second);

After executing these the results are:

enter image description here

Somehow part of minutes string is converted when converting hour string. Same with minutes and seconds.

The strings are placed side by side in the memory.

If I change the sequence of defining strings then seconds may be added to years etc.

Questions:

  • What may cause this error?
  • Is there any way to avoid this error with using atoi?

I know that I can convert using a loop one char at a time. Just trying to find why is it not working.


Solution

  • Besides the missing quotes around the strings your char array's size should be defined to hold one more char the EOS (end of string a binary zero).

    Since the memory representation would be e.g. "2014\0"

    char year[4+1] = "2014";