2010-05-18 233 views
3

我認爲這段代碼和錯誤是不言自明的,但我不知道爲什麼?

環境:
操作系統: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 

爲什麼我得到的格式警告,這可能是分段故障的原因?

回答

11
  1. 請使用-Wall編譯您的代碼。
  2. 包含inet_ntop的頭文件(arpa/inet.h)
  3. 請閱讀inet_ntop(3)手冊頁,並注意參數類型。
+0

+1很快的答案。 – Jack 2010-05-18 13:21:00

+0

它的工作。非常感謝你。 – ufengzh 2010-05-18 13:27:18

5

如果我算對,警告發出這條線:

printf(" address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str))); 

this pageinet_ntop確實返回char*。但是,顯然你不包括<arpa/inet.h> - 這可能會導致此警告,因爲編譯器可能會默認將未聲明的函數解釋爲返回int。

下一次,請用下劃線標出有問題的代碼行。評論 - 它會增加你獲得有用答案的機會:-)

+0

「編譯器可能會默認將未聲明的函數解釋爲返回int。」 你說得對,這是重點。 並感謝您的建議。 – ufengzh 2010-05-18 13:29:34

相關問題