[英]warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
I think this code and error is self-explanatory, but I don't know why? 我认为这段代码和错误是不言自明的,但我不知道为什么?
Environment: 环境:
OS: Mac OS X 10.6.1 操作系统:Mac OS X 10.6.1
Compiler: i686-apple-darwin10-gcc-4.2.1 编译器:i686-apple-darwin10-gcc-4.2.1
code: 码:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <netdb.h>
4 #include <sys/socket.h>
5
6 int
7 main(int argc, char **argv)
8 {
9 char *ptr, **pptr;
10 struct hostent *hptr;
11 char str[32];
12
13 //ptr = argv[1];
14 ptr = "www.google.com";
15
16 if ((hptr = gethostbyname(ptr)) == NULL) {
17 printf("gethostbyname error for host:%s\n", ptr);
18
19 }
20 printf("official hostname:%s\n", hptr->h_name);
21
22 for (pptr = hptr->h_aliases; *pptr != NULL; pptr++)
23 printf(" alias:%s\n", *pptr);
24
25 switch (hptr->h_addrtype) {
26 case AF_INET:
27 case AF_INET6:
28 pptr = hptr->h_addr_list;
29
30 for (; *pptr != NULL; pptr++)
31 printf(" address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
32 break;
33 default:
34 printf("unknown address type\n");
35 break;
36 }
37 return 0;
38 }
compiler and executed output below: 编译器和执行输出如下:
zhumatoMacBook:CProjects zhu$ gcc gethostbynamedemo.c
gethostbynamedemo.c: In function ‘main’:
gethostbynamedemo.c:31: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
zhumatoMacBook:CProjects zhu$ ./a.out
official hostname:www.l.google.com
alias:www.google.com
Segmentation fault
Why am I getting the format warning and could this be the cause of the segmentation fault? 为什么我会收到格式警告,这可能是分段错误的原因?
If I count right, the warning is emitted for this line: 如果我算数正确,则会为此行发出警告:
printf(" address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
According to this page , inet_ntop
does indeed return char*
. 根据这个页面 ,
inet_ntop
确实返回char*
。 However, apparently you don't include <arpa/inet.h>
- this can cause this warning, as the compiler may default to interpret an undeclared function as one returning an int. 但是,显然你没有包含
<arpa/inet.h>
- 这可能会导致出现此警告,因为编译器可能默认将未声明的函数解释为返回int的函数。
Next time, please mark the problematic code line(s) with eg a comment - it would increase your chances of getting useful answers :-) 下次,请用例如注释标记有问题的代码行 - 这会增加获得有用答案的机会:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.