代码之家  ›  专栏  ›  技术社区  ›  hora

从不兼容的指针类型警告传递参数

  •  4
  • hora  · 技术社区  · 15 年前

    我今天大部分时间都在试图找出C中的指针,甚至问A question 早些时候,但现在我被别的东西困住了。我有以下代码:

    typedef struct listnode *Node;
    typedef struct listnode {
        void *data;
        Node next;
        Node previous;
    } Listnode;
    
    typedef struct listhead *LIST;
    typedef struct listhead {
        int size; 
        Node first;
        Node last; 
        Node current; 
    } Listhead;
    
    #define MAXLISTS 50
    
    static Listhead headpool[MAXLISTS];
    static Listhead *headpoolp = headpool;
    
    #define MAXNODES 1000 
    
    static Listnode nodepool[MAXNODES];
    static Listnode *nodepoolp = nodepool;
    
    LIST *ListCreate()
    {
        if(headpool + MAXLISTS - headpoolp >= 1)
        {
            headpoolp->size = 0;
            headpoolp->first = NULL;
            headpoolp->last = NULL;
            headpoolp->current = NULL;
            headpoolp++;
            return &headpoolp-1; /* reference to old pointer */
    
        }else
            return NULL;
    }
    
    int ListCount(LIST list)
    {
        return list->size;
    
    }
    

    现在在一个新文件中,我有:

    #include <stdio.h>
    #include "the above file"
    
    main()
    {
        /* Make a new LIST */
        LIST *newlist; 
        newlist = ListCreate();
        int i = ListCount(newlist);
        printf("%d\n", i);
    }
    

    当我编译时,我得到以下警告 printf 声明打印了它应该打印的内容):

    file.c:9: warning: passing argument 1 of ‘ListCount’ from incompatible pointer type
    

    我应该担心这个警告吗?代码看起来像是按我想要的做,但是我显然对C中的指针很困惑。在浏览了这个站点上的问题后,我发现如果我把参数设置为listcount (void *) newlist ,我没有得到警告,我也不明白为什么,也不知道是什么。 (void *) 真的…

    任何帮助都将不胜感激,谢谢。

    1 回复  |  直到 15 年前
        1
  •  5
  •   Alok Singhal    15 年前

    由于有多个typedef,您会感到困惑。 LIST 是表示指向的指针的类型 struct listhead . 所以,你想要你的 ListCreate 函数返回 ,不是 LIST * :

    LIST ListCreate(void)
    

    上面说: ListCreate() 函数将返回指向新列表头的指针(如果可以)。

    然后你需要改变 return 函数定义中的语句 return &headpoolp-1; return headpoolp-1; . 这是因为您要返回最后一个可用的头部指针,并且您刚刚增加了 headpoolp . 现在你要从中减去1,然后返回它。

    最后,你的 main() 需要更新以反映上述更改:

    int main(void)
    {
        /* Make a new LIST */
        LIST newlist;  /* a pointer */
        newlist = ListCreate();
        int i = ListCount(newlist);
        printf("%d\n", i);
        return 0;
    }