Typing a pointer to struct

3

I was suggested to build a linked list using the following struct as a node:

typedef struct node *link;

struct node{
    int item;
    link next;
};

As I did not understand what the pointer operator along with this typedef I searched for, I ended up thinking that in this case link becomes a nickname for pointers to the node structure. Knowing this I started to create the list based on this idea, but at the beginning I already found errors, the code is compiled correctly, but the execution window crashes right after.

Code I'm getting:

int main ()
{
    link l;

    l->next = NULL;
}

I suppose I'm mistakenly using the nickname of the node pointer. What is the correct way to use it?

    
asked by anonymous 03.10.2015 / 16:14

1 answer

3

You have declared the variable but have not assigned any value to it. She tried to change her value. This causes error. You have to initialize the variable. Because it is a pointer, initialization is by memory allocation.

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

typedef struct node *link;

struct node{
    int item;
    link next;
};

int main(void) {
    link l = malloc(sizeof(struct node));
    l->next = NULL;
    return 0;
}

See running on ideone .

malloc() documentation . There's a lot to learn to use it. It's not as simple as it sounds.

Compilers can generate errors in these cases with proper configuration. When I compiled your code into ideone, it generated error. This saves a lot of time trying to find obscure errors.

    
03.10.2015 / 16:27