我認爲這段代碼和錯誤是不言自明的,但我不知道爲什麼?
環境:
操作系統:Mac OS X 10.6.1
編譯器:i686的-蘋果darwin10-GCC-4.2.1
代碼:警告:格式'%s'期望類型'char *',但參數2的類型爲'int'
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
爲什麼我得到的格式警告,這可能是分段故障的原因?
+1很快的答案。 – Jack 2010-05-18 13:21:00
它的工作。非常感謝你。 – ufengzh 2010-05-18 13:27:18