开发者

Strcmp comparing to identical strings but not entering loop

开发者 https://www.devze.com 2023-03-02 00:53 出处:网络
char* timecompare(){ char time[8]; snprintf(time,8,\"%i:%02i\",hour(),minute()); return time; } char* timefeed = \"8:0\";
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".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号