Arduino serial.print() 在实际字符后添加一个额外的字符
char *feedtime = "0:0";
String interval = "6";
char* convert(char* x, String y){
int hour;
int minute;
sscanf(x, "%d:%d", &hour, &minute);
char buf[5];
if (y == "6"){
if (hour > 17){
hour = (hour+6)%24;
snprintf(buf, 5, "%d%s", hour, ":0");
}
if (hour < 18){
hour = hour + 6;
snprintf(buf, 5, "%d%s", hour, ":0\0");
}
}
buf [5] = '\0';
return buf;
}
当我执行convert(time,interval);时
串行监视器返回正确的值,但会添加 ' 或其他符号。
有什么想法吗?
我根据人们的说法更新了我的代码,但是我仍然遇到同样的问题?
char *feedtime = "0:0";
String interval = "6";
char* convert(char* x, String y){
int hour;
int minute;
sscanf(x, "%d:%d", &hour, &minute);
char buf[5];
if (y == "6"){
if (hour > 17){
hour = (hour+6)%24;
snprintf(buf, 5, "%d%s", hour, ":0");
}
if (hour < 18){
hour = hour + 6;
snprintf(buf, 5, "%d%s", hour, ":0\0");
}
}
buf [5] = '\0';
return buf;
}
When I execute convert(time, interval);
the serial monitor returns the correct value but adds a ' or another symbol to it.
Any ideas why?
I updated my code from what people said, however I still get the same issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在返回一个指向堆栈变量的指针。这是错误的。一旦函数退出,“buf”使用的堆栈空间就不确定。
You are returning a pointer to a stack variable. This is wrong. Once the function exits the stack space used by 'buf' is undefined.
您的缓冲区中需要一个额外的字符。您只有 4 个字符的数组,但需要 5 个字符(2 个字符表示小时,2 个字符表示 :0,1 个字符表示尾随 0)。完成后,您还需要以 null 终止字符串。
以及杰科彭哈所说的话。
You need an extra character in your buffer. You only have a 4 character array, but you need 5 characters (2 for the hour, 2 for the :0, and 1 for the trailing 0). You also need to null terminate the string when you are done.
and what jcopenha says.
您的字符串没有正确以零结尾。增加buf的大小。
Your strings aren't properly zeroterminated. Increase the size of buf.