0

I am moving from Java to C and I am currently trying to design a linked list. In order to do this, I created a "node" structure which has a integer "val" attribute and a "dummy_element *next" attribute which is just a pointer to the next object. In the very beginning of the program, when it first starts running, no nodes should exist in memory, so I created a "Init_node()" function which creates a node called "first" and makes two external pointers "linked_head" and "linked_tail" point to the "first" node. Here is the relevant code:

    typedef struct dummy_element {
         int val;
         struct dummy_element *next;
    }node;

    node *linked_head;
    node *linked_tail;
    node *traversal

    void Init_node(){
        node first;
        first.val = NULL;
        first.next = NULL;
        linked_head = &first;
        linked_tail = &first;
    }

The whole point of the Init function is to initialize an empty node just so the pointers have something to point to. However, I keep getting the error "assignment makes integer from pointer without a cast" at first.val = NULL. Im not sure how to get around this error.

2 Answers 2

3

You want first.val = 0 instead of NULL. You should keep first.next = NULL which is correct.

In time you will encounter code that zeroes the structure using memset(&first, 0, sizeof first). While that also typically works, it has its problems (when all-bit-0 doesn't mean actual value of 0).


/* Once the function ends linked_head will be invalid. */
linked_head = &first; 

This is besides the point but I have to warn you. You are storing the address of an object (first) that will die when the function ends. You may want to use malloc to create your first, like so:

node *first = malloc(sizeof *first);
if (!first) {
    /* malloc failed, the process is in trouble. */
}

first->val = 0;
first->next = NULL;
linked_head = first;
Sign up to request clarification or add additional context in comments.

Comments

1

first.val is of type int but you are assigning it NULL which is of pointer type. Change it to 0.

first.val = 0;

Comments

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.