Search code examples
cmallocnodestypedef

implementing node using typedef vs not using typedef


I'm not sure if I understood the concept of typedef... Say there are two different ways of implementing nodes: one using typedef and another not using typedef. For example:

There's a node that was implemented like this: where a file named node1.c looks like:

struct node_int {
  int value;
  node next;
};
void init_node(node *n, int value) {
    node new_node = (node)malloc(sizeof(struct node_int));
    //some code for initializing
}

and in node1.h that looks like:

struct node_int;
typedef struct node_int *node;

and there's a node that was implemented like this: where a file named node2.c looks like:

struct node_int {
    int value;
    struct node *next;
};

void init_node(node_int **n, int value) {
    struct node_int* new_node = (struct node_int*)malloc(sizeof(struct node_int));
    //some code for initializing
}

and in node2.h that looks like:

struct node_int;

Are these two implementation equivalent? and is the use of malloc properly used on each cases? Any enlightenment would be appreciated.


Solution

  • Hiding pointers behind typedefs such as in typedef struct node_int *node; is error prone and confusing for many programmers. You should avoid doing it. You can simply use the same identifier for the struct tag and the typedef:

    typedef struct node node;
    
    struct node {
        int value;
        node *next;
    };
    
    node *init_node(int value) {
        node *np = malloc(sizeof(*np));
        if (np != NULL) {
            np->value = value;
            np->next = NULL;
        }
        return np;
    }