0

I am learning linked lists in C , and I don't understand these 2 lines:

struct LinkedList{
    int data;
    struct LinkedList *next;
 };

typedef struct LinkedList *node; //1

node createNode(){               //2
    node temp; 
    temp = (node)malloc(sizeof(struct LinkedList)); 
    temp->next = NULL;
    return temp;
}

In //1 What does it mean to assign a pointer as a name for the structure in typedef? and in //2 how can we have a function of the structure(node aka struct Linkedlist) ,as functions cannot be members of structures?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • `//1` is just like any other typedef. It creates a short name for a type, in this case `node` is equivalent to `struct LinkedList *` – Barmar Sep 07 '21 at 15:23
  • That's not a member of structure. It's a function that returns a `node`. – Barmar Sep 07 '21 at 15:23
  • 1
    Side notes: [do not cast the return of `malloc`](https://stackoverflow.com/a/605858/2505965), and [avoid empty parameter lists](https://stackoverflow.com/questions/41803937/func-vs-funcvoid-in-c99). – Oka Sep 07 '21 at 15:33
  • 1
    See [Is it a good idea to typedef pointers?](https://stackoverflow.com/q/750178/15168) — TL;DR, the answer is generally "No", with possible exceptions for function pointer types. – Jonathan Leffler Sep 07 '21 at 15:43

2 Answers2

3
  1. A typedef is like an alias. You're saying that node is struct LinkedList * (A pointer to an struct). You can then use node like you would use any type.

  2. That node is just the return value of the function. That function returns a new node

Iván
  • 971
  • 6
  • 20
1

This typedef declaration

typedef struct LinkedList *node;

introduces the type specifier node as an alias for the pointer type struct LinkedList *. So instead of writing

struct LinkedList * temp;

you my just write

node temp;

As for the function createNode

node createNode(){               //2
    node temp; 
    temp = (node)malloc(sizeof(struct LinkedList)); 
    temp->next = NULL;
    return temp;
}

then it is a standalone function. It is not a member of the structure. The function has the return type struct LinkedList * that is written by using its alias node.

Oka
  • 23,367
  • 6
  • 42
  • 53
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335