我一直试图在今天的大部分时间里找出C指针,甚至早些时候问了一个问题,但现在我还是坚持了其他的东西.我有以下代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个新文件:
#include <stdio.h>
#include "the above file"
main()
{
/* Make a new LIST */
LIST *newlist;
newlist = ListCreate();
int i = ListCount(newlist);
printf("%d\n", i);
}
Run Code Online (Sandbox Code Playgroud)
当我编译时,我得到以下警告(该printf
语句打印它应该是什么):
file.c:9: warning: passing argument 1 of ‘ListCount’ from incompatible pointer type
Run Code Online (Sandbox Code Playgroud)
我应该担心这个警告吗?代码似乎做了我想要的,但我显然对C中的指针非常困惑.在浏览了这个网站上的问题之后,我发现如果我向ListCount提出参数(void *) newlist
,我就不会收到警告,并且我不明白为什么,也不明白(void *)
......
任何帮助将不胜感激,谢谢.
你因为多个typedef而感到困惑. LIST
是表示指向的指针的类型struct listhead
.所以,你希望你的ListCreate
函数返回a LIST
,而不是LIST *
:
LIST ListCreate(void)
Run Code Online (Sandbox Code Playgroud)
上面说: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;
}
Run Code Online (Sandbox Code Playgroud)