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");
}
我将此作为我的代码,当 timecompare() 和 timefeed 都相等时它没有打印 hello?我这是一个指针问题?我不是将 timecompare() 与 timefeed 进行比较,而是将 timecompare() 与“8:0”进行比较,然后循环工作...这是 timefeed 变量的问题吗?
最佳答案
您正在从 timecompare()
返回堆栈分配的变量 time
。这是非法的,因为堆栈分配的内存仅在声明变量的函数中有效。
相反,您需要返回堆分配的字符串。您的编译器应该警告您这一点。你可以这样写:
char* timecompare(){
char* time = malloc(8);
snprintf(time,8,"%i:%02i",hour(),minute());
return time;
}
记得在用完后free()
内存。
关于c - strcmp 比较相同的字符串但不进入循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5827343/