Search code examples
ccharpebble-sdkcloudpebble

Pebble C, Getting Char at Specified Position


It's been a while since I last programmed using C, but it seems I'm confused with pointers and strings. I'm writing a Pebble watch face and I need to separate the digits for the minutes into the ones digit and the tens digit and put them into their respective containers.

So if the minutes is 25, I need to separate 2 and 5 and put them into two separate char variable.

The code I wrote is

static void update_time() {
  time_t temp = time(NULL);
  struct tm *tick_time = localtime(&temp);

  static char d_minute[] = "00";      

  if (clock_is_24h_style() == true)  {
    strftime(d_minute, sizeof("00"), "%M", tick_time);    
  } else {    
    strftime(d_minute, sizeof("00"), "%M", tick_time);    
  }     

  text_layer_set_text(s_m_one_layer, &d_minute[1]);  // ones' place for 2[5]
  text_layer_set_text(s_m_ten_layer, &d_minute[0]);  // tens' place for [2]5

}

The &d_minute[1] returns 5 correctly. However, &d_minute[0] returns the whole string, 25. What am I missing here? How can I access the first character in a char[]?

As an interim solution, what I did was to declare a 2-character char and strncpy &d_minute[0] into it, forcing it to copy just the first character.

 static char min_ten[] = "  ";
 .....
 strncpy(min_ten, &d_minute[0], 1);
 ....
 text_layer_set_text(s_m_ten_layer, min_ten);  

which I think is code smell. How do I get the tens' value in C?


Solution

  • Internally your d_minute string is stored like this:

    d_minute = {'2', '5', '\0'}
    

    the last character \0 terminates the string, by this way text_layer_set_text knows that the string has ended.

    When you call

    text_layer_set_text(&d_minute[0],...)
    

    then this is the equivalent of calling it like this

    text_layer_set_text(d_minute,...)
    

    You need to tell the function where the string you want to print ends, so your workaround is actually the right way to do it.