簡體   English   中英

C中的鏈表實現

[英]linked list implementation in c

我是c語言的新手,今天我正在嘗試在c語言中實現鏈接列表。

我只有一個函數調用createEmptyList()

# include <stdio.h>
# include <stdlib.h>
# include <time.h>



typedef struct Node
{
    int head;
    struct Node *next;
}LinkList;

LinkList* createEmptyLinkList(){
    LinkList* emptyList = malloc(sizeof(LinkList*));
    (*emptyList)->head = 0;
    (*emptyList)->next = NULL;

    return emptyList;
}

我正在嘗試使用指針初始化第一個節點。 但是,當我編譯時,出現以下錯誤:

linkedListImple.c:115:14: error: member reference type 'LinkList'
      (aka 'struct Node') is not a pointer; maybe you meant to use '.'?
        (*emptyList)->head = 0;
        ~~~~~~~~~~~~^~
                    .
linkedListImple.c:115:21: error: expression is not assignable
        (*emptyList)->head = 0;
        ~~~~~~~~~~~~~~~~~~ ^
linkedListImple.c:116:14: error: member reference type 'LinkList'
      (aka 'struct Node') is not a pointer; maybe you meant to use '.'?
        (*emptyList)->next = NULL;
        ~~~~~~~~~~~~^~
                    .
linkedListImple.c:116:21: error: expression is not assignable
        (*emptyList)->next = NULL;
        ~~~~~~~~~~~~~~~~~~ ^

我真的很困惑,即使我認為我在這里犯了一個非常基本的錯誤。

是不是在這里列出指針? 因為我將其聲明為LinkList * emptyList。 因此,如果emptyList是一個指針,則* emptyList是指實際的struct節點。

當我在以下幾行中刪除*號時,錯誤消失了。 它成為了:

    (emptyList)->head = 0;
    (emptyList)->next = NULL;

我也很困惑:兩者之間有什么區別

LinkList* emptyList = malloc(sizeof(LinkList*));

LinkList* emptyList = malloc(sizeof(LinkList));

他們都編譯良好。

非常感謝你。

sizeof(Something *)通常為您提供4個字節(作為地址),即地址的大小。

sizeOf(Something)為您提供對象的大小-在您的情況下,head(sizeof(int))可能是4個字節,指針(sizeof(address)-4個字節-假設您在這里的環境很多)。

請注意,正如喬納森·萊夫勒(Jonathan Lefler)指出的那樣,地址大小取決於OS體系結構。 可以通過(位數/ 8(字節的大小))來計算。 因此,在32位上,地址長4個字節,而在64位上,地址長可能是8個字節。

當您說(* SomeObject)表示指向時,您是在引用對象本身,因此可以使用(* SomeObject).property
當您具有對象的指針時。 您可以使用箭頭SomeObject-> property。 這將獲取SomeObject的引用並在其上找到一個“屬性”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM