Countdown

Hi,

a have a variable that contains the time in seconds.
Now I want a string (to send to a lcd) with hh:mm:ss.

    lcd.setCursor(0,1);
    lcd.print(convertTime(time));

char* convertTime(int time) {
char* hh;
char* mm;
char* ss;
int hhI;
int mmI;
int ssI;
hhI=time/3600;
mmI=(time-hhI*3600)/60;
ssI=time-hhI*3600-mmI*60;
itoa(hhI,hh,10);
itoa(mmI,mm,10);
itoa(ssI,ss,10);
strcat(hh,":");
strcat(hh,mm);
strcat(hh,":");
strcat(hh,ss);
return hh;
}

But somthings go wrong :frowning:

You did not allocate memory for the hh buffer.

Replace 'char* hh;' with:

static char hh[32] = {0};

The static is there, seeing you need the buffer to exist after the method returns.

What went wrong was that hh, mm, and ss are pointers to memory locations, but you never allocated any memory for them to point to, and you never made them point to anything.

Failing to have done that, hh, mm, and ss are equivalent to: char hh[1], mm[1], ss[1];

Then, itoa(hhI,hh,10); will write beyond the array bounds, since the terminating NULL that itoa adds to make a string is all that will actually fit in the array.

When you then try to concatenate a bunch more stuff:

strcat(hh,":");
strcat(hh,mm);
strcat(hh,":");
strcat(hh,ss);

that all fails to, since there is only room for one character in the array.

Finally, hh, mm, and ss are local variables that go out of scope at the end of the function, so you can not return them.

You can get around the problem by making the arrays fixed size and static, as leppie suggests, or by using malloc to dynamically allocate space for hh, mm, and ss, and then returning the pointer to the allocated space.

Since the return value is returned using pass by value, the value of the pointer (the memory location that was dynamically allocated) is copied into some local variable in the calling function. The hh variable still goes out of scope, but the memory that it points to is not freed when the pointer goes out of scope.

If you go this way, be sure to free the dynamically allocated space when you are done with it, to avoid running out of memory.

By the way,

But somthings go wrong

It's much more useful if you tell us [u]what/u goes wrong.

I think that you will get rid of a lot of this stress by having a look at the command:

“sprintf”

http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

You can write the string very easily.

The way it works is that you create a string which can hold “hh:mm:ss\0”.

static char buffer[9];

You then write the sprintf command as:

sprintf(buffer, “%d:%d:%d”, hh, mm, ss);

and each %d is replaced with the corresponding integer variable.

All you need to do is at the top of your code,

#include <stdio.h>

Paul, a "char *h" is NOT equivalent to "char h[1]", since the array points to something (one byte), where the pointer doesn't.

InvalidApple,

I think the format string "%02d:%02d:%02d" would work better for his purposes.

Regards,

-Mike

agreed :)