0

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

5
  • 1
    A struct can not hold an instance of the same type as itself. Commented Oct 7, 2014 at 19:20
  • 1
    You probably meant: struct Node *next = NULL; (i.e. missing *). Commented Oct 7, 2014 at 19:20
  • the temporary n should be a pointer Commented Oct 7, 2014 at 19:24
  • dont think c can have default values in structs. atleast not c99 Commented Oct 7, 2014 at 19:26
  • Your code is mixing typedef references with (the prefered method) struct references. Use one of the other, but not both Commented Oct 8, 2014 at 0:04

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

4 Comments

does the implementation see the Node definition? is some other header also defining Node?
I am not sure what you mean (new to c). I defined the struct just before the main function
@teaLeef, can you copy the code over to ideone to see it fully
Actually, it turns out the problem was that c99 can't have default values in structs. Thanks for your help
1

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;
}

1 Comment

I tried with this method, but when I call 'Node lr;' 'lr.number = 0;' 'add_node(&lr,2);'I get a seg fault. Any idea what is wrong?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.