[英]warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
我認為這段代碼和錯誤是不言自明的,但我不知道為什么?
環境:
操作系統:Mac OS X 10.6.1
編譯器:i686-apple-darwin10-gcc-4.2.1
碼:
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 }
編譯器和執行輸出如下:
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
為什么我會收到格式警告,這可能是分段錯誤的原因?
如果我算數正確,則會為此行發出警告:
printf(" address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
根據這個頁面 , inet_ntop
確實返回char*
。 但是,顯然你沒有包含<arpa/inet.h>
- 這可能會導致出現此警告,因為編譯器可能默認將未聲明的函數解釋為返回int的函數。
下次,請用例如注釋標記有問題的代碼行 - 這會增加獲得有用答案的機會:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.