Keil 中的 sprintf 恼人警告
sprintf annoying warning in Keil
我正在尝试在 Keil 中使用 sprintf();
函数。但我有烦人的警告。让我用下面的示例代码部分解释我的警告。当我调试时,我得到;
warning: #167-D: argument of type "uint8_t *" is incompatible with parameter of type "char *restrict"
它在线上就格式类型向我发出警告。
我知道 sprintf 函数不是一个好的解决方案,但我真的很想知道为什么要显示此警告?
谢谢
#include "stm32l0xx.h" // Device header
#include <stdio.h>
void LCD_show(uint32_t s_value)
{
uint8_t str[9], i;
for ( i = 0; i < 9 ; i++) str[i] = 0;
sprintf( str, "%9ld", s_value );
}
uint8_t
和 char
不一定是一回事。通常实际上它的类型定义为 unsigned char
.
正在修复您的警告:
您有两个选择:要么将 str
声明为 char
,要么使用类型转换:
sprintf((char *) str, "%9ld", s_value);
优化您的代码:
出现循环的唯一原因是用零初始化 str
数组。以下是以简单易读的方式执行此操作的代码,没有代码开销:
char str[9] = {0};
正在修复您的代码:
文档摘录:
A format specifier follows this prototype:
%[flags][width][.precision][length]specifier
...
Width:
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
这意味着您的代码最终会出现缓冲区溢出并崩溃。使用 snprintf
!
我正在尝试在 Keil 中使用 sprintf();
函数。但我有烦人的警告。让我用下面的示例代码部分解释我的警告。当我调试时,我得到;
warning: #167-D: argument of type "uint8_t *" is incompatible with parameter of type "char *restrict"
它在线上就格式类型向我发出警告。
我知道 sprintf 函数不是一个好的解决方案,但我真的很想知道为什么要显示此警告?
谢谢
#include "stm32l0xx.h" // Device header
#include <stdio.h>
void LCD_show(uint32_t s_value)
{
uint8_t str[9], i;
for ( i = 0; i < 9 ; i++) str[i] = 0;
sprintf( str, "%9ld", s_value );
}
uint8_t
和 char
不一定是一回事。通常实际上它的类型定义为 unsigned char
.
正在修复您的警告:
您有两个选择:要么将 str
声明为 char
,要么使用类型转换:
sprintf((char *) str, "%9ld", s_value);
优化您的代码:
出现循环的唯一原因是用零初始化 str
数组。以下是以简单易读的方式执行此操作的代码,没有代码开销:
char str[9] = {0};
正在修复您的代码:
文档摘录:
A format specifier follows this prototype:
%[flags][width][.precision][length]specifier
...
Width:
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
这意味着您的代码最终会出现缓冲区溢出并崩溃。使用 snprintf
!