我是c編程和閱讀c入門的入門書:第5版。令我困惑的是爲什麼plist
作爲指向List的指針還可以指向Node?爲什麼指向List的指針也可以指向Node?
對不起,我沒有將函數ListItemCount粘貼到代碼塊。在這個函數中,Node * pnode = *plist;
,這是否意味着plist
被轉換爲Node
?如果是這樣,爲什麼程序需要轉換爲指向節點的指針,而不是將plist->head
指定爲pnode
(指向節點的指針)?
typedef struct film {
char title[TSIZE];
int rating;
} Item;
typedef struct node{
Item item;
// typical usage
struct node * next;
} Node;
/*
* Note: to manage a linked list, we need a pointer to its beginning,
* and we've used typedef to make List the name for a pointer of this
* type.
*/
typedef struct list{
// should point to linked list Node
Node * head;
int size;
} List;
// TODO why `plist` as a pointer to List can also point to Node?
/* returns number of nodes */
unsigned int ListItemCount(const List * plist)
{
unsigned int count = 0;
Node * pnode = *plist; /* set to start of list */
while (pnode != NULL)
{
++count;
pnode = pnode->next; /* set to next node */
}
return count;
}
指針可以指向任何東西。當你試圖從所述指針讀取「有意義的」數據時,事情就會出錯。如果你試圖將'List'指針轉換爲'Node'指針,你肯定會得到一些編譯器警告。 –
它不能,不是真的。爲什麼你這麼想?你能詳細說明一下你會困惑嗎? –
在你的代碼片段'plist'根本不使用。 – VTT