【问题标题】:warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’警告:格式“%s”需要类型“char *”,但参数 2 的类型为“int”
【发布时间】:2010-05-18 13:13:29
【问题描述】:

我认为这段代码和错误是不言自明的,但我不知道为什么?

环境:
操作系统: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

为什么我会收到格式警告,这可能是分段错误的原因吗?

【问题讨论】:

    标签: c gcc printf


    【解决方案1】:
    1. 请使用 -Wall 编译您的代码。
    2. 包含 inet_ntop 的头文件 (arpa/inet.h)
    3. 阅读 inet_ntop(3) 手册页并注意参数类型。

    【讨论】:

      【解决方案2】:

      如果我数对了,就会针对这一行发出警告:

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

      根据this pageinet_ntop 确实返回了char*。但是,显然您没有包含 &lt;arpa/inet.h&gt; - 这可能会导致此警告,因为编译器可能默认将未声明的函数解释为返回 int 的函数。

      下次,请将有问题的代码行标记为例如评论 - 它会增加您获得有用答案的机会:-)

      【讨论】:

      • “编译器可能默认将未声明的函数解释为返回 int 的函数。”你是对的,这就是重点。并感谢您的建议。
      猜你喜欢
      • 1970-01-01
      • 2013-05-10
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多