简体   繁体   中英

linked list implementation in c

I'm new to c and today I'm trying to implement linked list in c.

I only have one function call 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;
}

I'm trying to use pointer to initialize the first node. However when i compile, i get the following error:

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;
        ~~~~~~~~~~~~~~~~~~ ^

I'm really confused, even though i think i've made a very basic mistake here.

Isn't emptyList a pointer here? since I declare it as LinkList* emptyList. So if emptyList is a pointer, then *emptyList refer to the actual struct node.

when i delete the * sign in following lines, the error disappears. it becomes:

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

Also i'm confused about: what's the difference between

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

and

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

They both compile fine.

Thank you very much.

sizeof(Something *) gives you usually 4 bytes (as an address), which is the size of an Address.

sizeOf(Something) gives you the size of your object - in your case it might be 4 bytes for the head(sizeof(int)) and 4 bytes for the pointer (sizeof(address) - assuming a lot about your environment here ).

Note that, as pointed out by Jonathan Lefler, address size depends on the OS architecture. It can be calculated by (number of bits / 8 (the size of a byte)). So, on 32bits, addresses are 4 bytes long and on 64 bits, they may be 8 bytes long.

when you say (*SomeObject) which means pointed by, you are referencing the object itself, so you can use (*SomeObject).property
when you have the pointer of the Object. you can use the arrow SomeObject->property. which will get the reference of SomeObject and find a "property" on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM