开发者

Passing argument from incompatible pointer type warning

开发者 https://www.devze.com 2022-12-19 00:15 出处:网络
I\'ve been trying to figure out pointers in C most of today, even asked a question earlier, but now I\'m stuck on something else. I\'ve got the following code:

I've been trying to figure out pointers in C most of today, even asked a question earlier, but now I'm stuck on something else. I've got the following code:

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];
st开发者_运维百科atic 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;

}

Now in a new file I have:

#include <stdio.h>
#include "the above file"

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

When I compile, I get the following warning (the printf statement prints what it should):

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

Should I be worried about this warning? The code seems to do what I want it to, but I'm obviously very confused about pointers in C. After browsing questions on this site, I found that if I make the argument to ListCount (void *) newlist, I don't get the warning, and I don't understand why, nor what (void *) really does...

Any help would be appreciated, thanks.


You're getting confused because of multiple typedefs. LIST is a type representing a pointer to struct listhead. So, you want your ListCreate function to return a LIST, not a LIST *:

LIST ListCreate(void)

The above says: ListCreate() function will return a pointer to a new list's head if it can.

Then you need to change the return statement in the function definition from return &headpoolp-1; to return headpoolp-1;. This is because you want to return the last available head pointer, and you have just incremented headpoolp. So now you want to subtract 1 from it and return that.

Finally, your main() needs to be update to reflect the above changes:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号