Strcmp comparing to identical strings but not entering loop
char* timecompare(){
char time[8];
snprintf(time,8,"%i:%02i",hour(),minute());
return time;
}
char* timefeed = "8:0";
if (strcmp(timecompare(), timefeed) == 0){
Serial.println("hello");
}
I have this as my code when timecompare() and timefeed are both equal it is not printing hello开发者_Go百科? I this a pointer problem? I instead of comparing timecompare() with timefeed I compare timecompare() with "8:0" then the loop works... Is this a problem with the timefeed variable?
You are returning a stack allocated variable, time
, from timecompare()
. This is illegal since stack allocated memory is only valid in the function in which the variable is declared.
Instead you need to return a heap allocated string. Your compiler should be warning you of this. You could write it like this:
char* timecompare(){
char* time = malloc(8);
snprintf(time,8,"%i:%02i",hour(),minute());
return time;
}
Remember to free()
the memory after you are finished with it.
You return a local variable time
out of its scope. When you exit the function timecompare
, the returned value is no longer a valid pointer.
Also, remove the "02" from the %02i
, it should be %i
if you compare it to 8:0. Using %02i
will yield "00".
精彩评论