Typing a pointer to struct

Asked

Viewed 152 times

4

I was suggested to build a chained list using the following struct knotted:

typedef struct node *link;

struct node{
    int item;
    link next;
};

As I did not understand what the pointer operator means along with this typedef I researched and ended up thinking that in this case link becomes an alias for pointers to the structure node. Knowing this I started to create the list based on this idea, but at first I found errors, the code is compiled correctly, but the execution window hangs soon after.

Code that I’m starting:

int main ()
{
    link l;

    l->next = NULL;
}

I suppose I am using the "nickname" of the Node pointer erroneously. What is the correct way to use it?

1 answer

4


You declared the variable but did not assign any value to it. Then you tried to modify its value. This generates error. You have to initialize the variable. Because it is a pointer, the initialization takes place 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;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Documentation of malloc(). There is much to learn to use it. It is not as simple as it seems.

Compilers can generate error in these cases with proper configuration. When I compiled your code in ideone it generated error. It saves a lot of time trying to find dark mistakes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.