snprintf的 - 格式不是字符串文字,没有格式参数警告 [英] snprintf - format not a string literal and no format arguments warning
问题描述
我得到格式不是一个字符串文字,没有格式参数
警告,当我编译它在Linux上。 的snprintf 显示为const char *
的第三个参数。什么是错的定义为const char *接口=为wlan0
然后将它传递给函数?
的#include<&stdio.h中GT;
#包括LT&;净/ if.h中>
#包括LT&;&string.h中GT;INT主(INT ARGC,CHAR *的argv []){
为const char *接口=为wlan0
结构的ifreq IFR; memset的(安培; IFR,0,sizeof的(IFR));
的snprintf(ifr.ifr_name,sizeof的(ifr.ifr_name),接口); 返回0;
}
这是没有错的(这就是为什么它是一个警告而不是错误),这只是最常用的的printf 的code>系列函数使用的文字的格式字符串。
我爱:
的snprintf(ifr.ifr_name,sizeof的(ifr.ifr_name),%S,接口);
在你的情况,你或许应该使用例如 的memcpy
而不是:
的#define MIN(A,B)((一)≤(B)(A):(B))的memcpy(ifr.ifr_name,接口,MIN(strlen的(接口)+ 1的sizeof(ifr.ifr_name));
还有 函数strncpy
这可能会工作,但它的时候不会增加终端的情况下'\\ 0'
字符。
I get format not a string literal and no format arguments
warning when I compile it on Linux. snprintf shows const char*
for the third parameter. What is wrong to define const char *INTERFACE = "wlan0"
then pass it to the function?
#include <stdio.h>
#include <net/if.h>
#include <string.h>
int main(int argc,char *argv[]){
const char *INTERFACE = "wlan0";
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), INTERFACE);
return 0;
}
It's nothing wrong (that's why it's a warning and not an error), it's just that the most common use of the printf
family of function uses a literal format string.
Like:
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", INTERFACE);
In your case you should probably be using e.g. memcpy
instead:
#define MIN(a, b) ((a) < (b) ? (a) : (b))
memcpy(ifr.ifr_name, INTERFACE, MIN(strlen(INTERFACE) + 1, sizeof(ifr.ifr_name));
There's also strncpy
which might work, but there is a case when it will not add the terminating '\0'
character.
这篇关于snprintf的 - 格式不是字符串文字,没有格式参数警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!