【发布时间】:2011-01-10 18:02:35
【问题描述】:
我今天大部分时间都在尝试找出 C 语言中的指针,甚至早些时候问过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 *) 到底做了什么......
任何帮助将不胜感激,谢谢。
【问题讨论】:
-
ListCount 接受 LIST 吗?什么是列表?它在哪里定义?你通过它 LIST*
-
如果您没有
typedef指针类型,代码会更容易阅读/调试。 -
从我有限的理解来看,LIST 是一个指向结构体的指针,叫做 Listhead。我说的对吗?
-
@hora:
typedef struct listhead LIST和typedef struct listhead *LIST之间存在差异。第一种情况LIST是struct listhead的同义词,第二种情况是struct listhead *的同义词。 -
@hora:很多人(包括我在内)都认为从不 typedef 去掉指针是个好主意,只需 typedef 结构。隐藏星号是个坏主意,因为它通常会在您使用该类型时突然出现,而且只会令人困惑。