2

Hello I am so confused about this, I hope you can help me. Here is my code:

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

struct node{
    int x;
    struct node *next;
    struct node *prev;
};

typedef struct node NODE;

NODE * create(int data)
{
    NODE *newn;
    newn=(NODE*)malloc(sizeof(NODE));
    newn->x=data;
    newn->next=NULL;
    newn->prev=NULL;
    return newn;
}

int insert(NODE *list, int data)
{
    NODE *temp,*news;
    temp=list;
    if(list==NULL)
    {
        list=create(data);
        return 0;
    }
}

int main()
{
    int put;
    NODE *mList=NULL;
    clrscr();
    printf("data: ");
    scanf("%i",&put);         
    insert(mList,put);                
}

It is a very simple doubly linked list but I cannot even start inserting because I cannot even put value into the first node. When I create the new node in create, the newn->x will have the right value, and list->x (in insert) will also have the right value but when it goes back to main, mList->x is still 0.

2 Answers 2

4

You're passing the mList pointer by value, therefore it resets when the function returns.

Switch to

insert(NODE** list, int data) 

and pass it by

insert(&mList, put); 

Then I think it'll work. Everytime you want a function to change something you need to pass the argument by pointer, or possibly by reference if you ever move to C++.

Sign up to request clarification or add additional context in comments.

1 Comment

Since there are no references in C, the option in your last setence isn't any.
0

I am actually surprised that mList is non-zero after the call to insert.

When you pass mList to insert, a copy of the pointer (mList, which is NULL) is passed to insert. This means that whatever you do with the pointer "list" in the insert function is not reflected in the variable mList (which is outside the function).

You will need to pass address of mList so that you can change what it is pointing to.

So, change the insert method to:

insert(NODE** list, int data)

Change the assignement to list to:

*list = create(data);

and change the call to insert to:

insert(&mList, put);

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.