1

MY function to create a linked list was

 void create(node *list)
 {
    fscanf(fp,"%d\t",&list->number);
      if(list->number==0)
           {
                list=NULL;
           }
     else
           {
           list->next=(node *)malloc(sizeof(node));
           create(list->next);
           }
            return;

      }

INPUT in my txt file was like

1 37 79 164 155 32 87 39 113 15 18 78 175 140 200 0

2 4 160 97 191 100 91 20 69 198 196 0

Now when i am trying to access the 0 through head->next->next.....->number even though i have assigned null pointer in the if statement when the input is 0,the output is being shown as 0

Also i tried changing the if statement to free(list); now i am able to access the elements in the next row just by adding more (next->) b/w head and number

 struct linked_list  //structure of node
        {
       int number;
       struct linked_list *next;
        };

Please explain me why the program is behaving like this

1 Answer 1

2

Here:

list = NULL;

You are assigning NULL to a local pointer list, but the real pointer does not change.

You can only manipulate the data, pointer refers to. If you want to change a pointer, you have to pass pointer to pointer as function parameter. But I suggest you rewrite your function like this:

node* inputNode()
{
    int number = 0;
    fscanf(fp, "%d\t", &number);

    node* n = NULL;

    if(number != 0)
    {
        node = (node *)malloc(sizeof(node));
        node->number = number;
        node->next = NULL;
    }

    return node;
}


node* createList()
{
    node* root = inputNode();
    node* curr = root;

    while(curr != NULL)
    {
        curr->next = inputNode();
        curr = curr->next;
    }

    return root;
}
Sign up to request clarification or add additional context in comments.

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.