Go Down

Topic: Odd sprintf behaviour (Read 1 time) previous topic - next topic


I have the following code:
Code: [Select]
#include <DS3231.h>
#include <Wire.h>
#include <stdio.h>

DS3231 Clock;
bool Century = false;
bool h12;
bool PM;

char currDate[24];
char currTime[22];

long lastRun = 0;
int pause = 1000;

void setup() {

void loop() {
 if (millis() - lastRun > pause) {
   sprintf(currDate, "Current Date: 20%02d/%02d/%02d", Clock.getYear(), Clock.getMonth(Century), Clock.getDate());
   sprintf(currTime, "Current Time: %02d:%02d:%02d", Clock.getHour(h12, PM), Clock.getMinute(), Clock.getSecond());



   lastRun = millis();

And the output I'm getting is:
Code: [Select]
Current Date: 2013/01/13Current Time: 23:31:49
Current Time: 23:31:49

Current Date: 2013/01/13Current Time: 23:31:50
Current Time: 23:31:50

Current Date: 2013/01/13Current Time: 23:31:51
Current Time: 23:31:51

Can anyone explain to me why it appears that the 'currTime' variable gets tacked onto the end of the 'currDate' one?  If I just output 'currDate', I get:
Code: [Select]
Current Date: 2013/01/13Current Time: 23:32:27

Why's that?


I would guess you have to add a Line feed in there.
The way you have it in your schematic isn't the same as how you have it wired up!


LarryD, read (or reread) the entire post and code before you answer.  'currDate' does *not* contain the time variables in it.


You haven't allocated space for a null terminator in the currDate array, and as luck would have it the next block of memory is the currTime array.

You want to allocate 1 more than the longest string to allow for a null terminator (\0) otherwise when you print it will keep reading memory as a string until it hits a null.

You really want to allocate your arrays as
Code: [Select]

char currDate[25];
char currTime[23];


Lovely.  That explains a lot.  Though it doesn't explain why I never encountered that before in other languages that also use printf() and sprintf() ...  Oh well.  Thanks SPD.

Go Up