警告可能出现的问题:
directive output truncated writing 16 bytes into a region of size 4 [-Wformat-truncation=]
warning: argument to ‘sizeof’ in ‘snprintf’ call is the same expression as the destination; did you mean to provide an explicit length? [-Wsizeof-pointer-memaccess]
note: assuming directive output of 4 bytes
出现了问题记录一下,防止脑子不好忘记了。
直接上代码看情况:
在main函数中调用了report_tempRH_json,传入buf,获取数据。但是获取的数据是不全的。
#include <stdio.h>
void report_tempRH_json(char *buf);
int main(int argc, char *argv[])
{
char temp_hum_buf[256];
report_tempRH_json(temp_hum_buf);
printf("temp_hum_buf:%s\n", temp_hum_buf);
return 0;
}
void report_tempRH_json(char *buf)
{
float temperature = 66.6666;
float humidity = 55.5555;
snprintf(buf, sizeof(buf), "{\"Temperature\":\"%.2f\", \"Humidity\":\"%.2f\"}", temperature, humidity);
printf("buf:%s\n", buf);
}
找了一圈没找到答案,最后发现,sizeof(buf)这儿出现了问题:
在main主函数中sizeof(buf)=256
在自定义函数中sizeof(buf)=8
所以字节在自定义函数中将sizeof(buf)改成256就可,或者宏定义大小,比较方便。
#include <stdio.h>
void report_tempRH_json(char *buf);
int main(int argc, char *argv[])
{
char temp_hum_buf[256];
report_tempRH_json(temp_hum_buf);
printf("Main function sizeof(temp_hum_buf): %d\n", sizeof(temp_hum_buf));
printf("temp_hum_buf:%s\n", temp_hum_buf);
return 0;
}
void report_tempRH_json(char *buf)
{
float temperature = 66.6666;
float humidity = 55.5555;
snprintf(buf, 256, "{\"Temperature\":\"%.2f\", \"Humidity\":\"%.2f\"}", temperature, humidity);
printf("Custom function sizeof(buf): %s\n", buf);
printf("sizeof(buf): %d\n", sizeof(buf));
}
但是在实际情况下我们不会传buf的,一般是一个函数就实现一个功能,我们的目的是在buf中放数据,那就直接在自定义函数中进行就可以了呗。并且buf用完之后出了自定义函数之后就释放了,方便。
#include <stdio.h>
void report_tempRH_json();
int main(int argc, char *argv[])
{
report_tempRH_json();
return 0;
}
void report_tempRH_json()
{
char buf[256];
float temperature = 66.6666;
float humidity = 55.5555;
snprintf(buf, sizeof(buf), "{\"Temperature\":\"%.2f\", \"Humidity\":\"%.2f\"}", temperature, humidity);
printf("sizeof(buf): %s\n", buf);
printf("sizeof(buf): %d\n", sizeof(buf));
}