teaLeef
teaLeef

Reputation: 1989

Using structures in a linked list

I am trying to create an append_node method to add a node to a linked list I created. My Node structure is defined below:

typedef struct Node{
    struct Node next = NULL;
    int id;
} Node;

However, when compiling with the method below, I get the following error: 'Node' has no member named 'id' 'Node' has no member named 'next'

void append_node(Node *sent,int val){   
    Node *other_node = (struct Node *)malloc(1*sizeof(struct Node));
    other_node->id = val;
    Node n = *sent;
    while (n.next != NULL){
        n = n.next;
    }
    n.next = other_node;
}

Why is this error occurring?

EDIT:

I also have the following error

error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token

on the first line of the Node definition

Upvotes: 0

Views: 91

Answers (2)

radar
radar

Reputation: 13425

You can't have Node defined again inside the same structure. This will be infinite recursion.

you can have a Pointer to the same type.

typedef struct Node{
    struct Node *next;

Upvotes: 2

sp2danny
sp2danny

Reputation: 7687

there are numerous errors in your code.
here is a correct version

typedef struct NodeTag
{
    struct NodeTag* next;
    int id;
} Node;

void append_node(Node* sent,int val)
{   
    Node* other_node = (Node*)malloc(sizeof(Node));
    other_node->id = val;
    other_node->next = 0;
    Node* n = sent;
    while (n->next != 0)
    {
        n = n->next;
    }
    n->next = other_node;
}

Upvotes: 1

Related Questions