sve*_*ven 4 c linux printf gcc posix
format not a string literal and no format arguments当我在 Linux 上编译它时,我收到警告。snprintf显示const char*第三个参数。const char *INTERFACE = "wlan0"定义然后将其传递给函数有什么问题 ?
#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;
}
Run Code Online (Sandbox Code Playgroud)
这没有什么问题(这就是为什么它是警告而不是错误),只是该函数系列最常见的用法printf使用文字格式字符串。
喜欢:
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", INTERFACE);
Run Code Online (Sandbox Code Playgroud)
在你的情况下,你可能应该使用例如memcpy:
#define MIN(a, b) ((a) < (b) ? (a) : (b))
memcpy(ifr.ifr_name, INTERFACE, MIN(strlen(INTERFACE) + 1, sizeof(ifr.ifr_name));
Run Code Online (Sandbox Code Playgroud)
还有strncpy一种可能有效,但在某些情况下它不会添加终止'\0'字符。