Strcmp 与相同字符串进行比较但不进入循环
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 变量的问题吗?
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? 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将从
timecompare()
返回一个堆栈分配变量time
。这是非法的,因为堆栈分配的内存仅在声明变量的函数中有效。相反,您需要返回一个堆分配的字符串。你的编译器应该警告你这一点。你可以这样写:
使用完内存后记得
free()
内存。You are returning a stack allocated variable,
time
, fromtimecompare()
. 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:
Remember to
free()
the memory after you are finished with it.您返回超出其范围的局部变量
time
。当退出函数timecompare
时,返回值不再是有效的指针。另外,将
%02i
中的“02”去掉,如果与 8:0 比较,它应该是%i
。使用%02i
将产生“00”。You return a local variable
time
out of its scope. When you exit the functiontimecompare
, 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".