Reputation: 3516
Working with arduino. I have the following code in a function that is run twice during a process:
int hours = 7;
char hour = hours+'0';
debug(&hour);
char hour2 = hours+'0';
debug(&hour2);
The debug
function is:
void debug(char message[]) {
if (debugEnabled == true) {
Serial.println(message);
}
}
The global debugEnabled
flag is initialized to true
.
I'm getting the following output from every time the full process runs (hence executing the first code block twice):
7
7
72
7
I can't see any reason I'm getting 72 in there on the second time the first variable is written, especially as the hour2
variable is printed correctly every time.
Any suggestions as to what might be going wrong or how to further debug this would be very appreciated.
Upvotes: 1
Views: 61
Reputation: 409364
Because you treat a single character as a string. A string in C needs to be terminated by an extra '\0'
character. All string handling functions continue until they find this terminator character, and will go beyond any array limits you may have and producing unexpected and undefined results.
Upvotes: 5