【问题标题】:Strange pointer warning while printing directory listing打印目录列表时出现奇怪的指针警告
【发布时间】:2013-10-08 13:43:43
【问题描述】:

我有以下代码来打印 unix 中的目录列表。

struct dirent *res;
struct DIR *dir;
scanf("%s",str);
dir=opendir(str);
if(dir==NULL)
{
    perror("Invalid directory");
    return 1;
}
res=(struct dirent *)readdir(dir);
while(res)
{
    printf("%s\n",res->d_name);
    res=(struct dirent *)readdir(dir);
}

当我编译上述代码时,我收到以下警告

ls.c:16:17: warning: passing argument 1 of ‘readdir’ from incompatible pointer type   
      [enabled by default]
/usr/include/dirent.h:164:23: note: expected ‘struct DIR *’ but argument is of type 
     ‘struct DIR *’
ls.c:20:21: warning: passing argument 1 of ‘readdir’ from incompatible pointer type  
    [enabled by default]
/usr/include/dirent.h:164:23: note: expected ‘struct DIR *’ but argument is of type 
    ‘struct DIR *’

当 GCC 说“预期参数 foo 但参数类型为 foo”时,GCC 到底是什么意思?

我也尝试使用struct DIR dir 代替*dir&dir 代替dir,但会导致以下错误

ls.c:7:12: error: storage size of ‘dir’ isn’t known

PS:代码的输出是完全OK的。

【问题讨论】:

    标签: c


    【解决方案1】:

    DIR 是一个宏,通常扩展为struct something,因此您声明struct struct something *dir。这显然是一件令人困惑的事情(尽管 GCC 显然也很好),导致了令人困惑的错误消息。解决方案是简单地声明DIR *dir,而不使用struct

    【讨论】:

    • 顺便说一句,我非常感兴趣,所以我查找了相关的语法......至少在 C99 中,struct struct foo 是非法的。
    【解决方案2】:

    Ben 对您的问题有正确的解决方案,但这看起来确实是 gcc 如何报告此错误的一个严重问题。

    首先,这不是宏观问题。 DIRstruct __DIR 的 typedef(至少这里是这样,我得到相同的错误消息)。除了struct DIR *dir; 声明的那个之外,没有struct DIR,但gcc 似乎在说还有另一种具有该名称的类型。

    这个示例编译单元更清楚地说明了这个问题:

    struct foo {
      int a,b,c;
    };
    
    typedef struct foo bar;
    
    void do_bar(bar *);
    
    void func(void)
    {
      int i = 0;
    
      /* do_bar wants a bar *, which is a struct foo *, but we're giving it an
         int * instead. What will gcc say? */
      do_bar(&i);
    }
    

    gcc 报告:

    t.c: In function ‘func’:
    t.c:15:7: warning: passing argument 1 of ‘do_bar’ from incompatible pointer type [enabled by default]
    t.c:7:10: note: expected ‘struct bar *’ but argument is of type ‘int *’
    

    但代码中根本没有struct bar。它采用了bar typedef 并无缘无故地在其前面塞满了struct 这个词。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      相关资源
      最近更新 更多