I'm having problems getting sprintf() to work on a Mega 2560. The code I use always works when it is put directly into the loop, but when I put it into a function, it causes the Arduino to (seemingly) reset once the function returns.
This does NOT divide numRemaining by 10 and then write the result as an int with at least two places. It writes the int with a minimum pf two places (could be more) then the string "/10" and a NULL. That's 6 or more elements that you are trying to fit in a 5 element array.
Just to clarify, why would this have worked in the loop?
You are writing off the end of the array. That never works, for my definition of work. What is possibly did in your case was step on some memory that you didn't notice got stepped on. When you put the code in a function, what is likely stepped on is the return address. THAT you do notice getting stepped on.
It likely means that it found a null somewhere nearby in memory your string didn't own, but that was good enough that you saw no ill effects.
For future reference, all strings should have a null termination at the end - that is the only thing that makes a string distinguishable from an array.
gwsmyda:
I didn't realize that sprintf terminated with a NULL.
While sprintf() does add a NULL to the end, this isn't a sprintf() thing.
All strings in C are terminated with a NULL, that is how the end of the string is marked.
So "hello" takes up 6 bytes
and "%2i/10" takes up 7 bytes.
PeterH:
This sort of problem is avoided if you use snprintf() instead of sprintf().
But only if you specify the correct size for the array, and only if you understand that snprintf() will NOT generate the output you expect if the array is too small.
Better to make the array large enough in the first place. IMHO.