Search code examples
csizeofstrlenprintfpebble-sdk

snprintf + Pebble


I'm developing for Pebble and I'm off to a rough start.

I'm trying to populate a text_layer with 2 strings and 2 values, something like this:

WAIT AVG: 3 MAX: 5

Since malloc is not supported in Pebble SDK, I can't use sprintf, hence I'm stuck with snprintf. The following code only prints "4":

srand(time(NULL));
int average = (rand()%6)+1; 
int maximum = average + 2;
static char *avgText="WAIT AVG: ";
static char *maxText="MAX: ";
snprintf(labelText,sizeof(avgText) + sizeof(average) + sizeof(maxText) + sizeof(maximum),"%s %d %s %d",avgText,average,maxText,maximum);

Any help would be greatly appreciated. I know that I can create 4 separate TextLayers but that's kind of a last resort for me.


Solution

  • You're just using snprintf wrong. ;-)

    The second parameter (which you're trying to calculate, badly) is the length of the character array that you're printing into, not the number of characters you're trying to write.

    Something like this should work:

    char labelText[64]; // Is this big enough?
    snprintf(labelText, 64,"%s %d %s %d",avgText,average,maxText,maximum);