Strcmp 与相同字符串进行比较但不进入循环

发布于 2024-11-03 16:45:33 字数 397 浏览 2 评论 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"); 
}

当 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

流心雨 2024-11-10 16:45:33

您将从 timecompare() 返回一个堆栈分配变量 time。这是非法的,因为堆栈分配的内存仅在声明变量的函数中有效。

相反,您需要返回一个堆分配的字符串。你的编译器应该警告你这一点。你可以这样写:

char* timecompare(){
    char* time = malloc(8);
    snprintf(time,8,"%i:%02i",hour(),minute());
    return time;
}

使用完内存后记得free()内存。

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.

随波逐流 2024-11-10 16:45:33

您返回超出其范围的局部变量time。当退出函数timecompare时,返回值不再是有效的指针。

另外,将 %02i 中的“02”去掉,如果与 8:0 比较,它应该是 %i。使用 %02i 将产生“00”。

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".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文