1

Here is my code :

typedef struct node {
    int data;
    struct node *next;
} Node;

void add(Node *head, Node *node) {
    Node *ptr;
    ptr = head;
    if(head==NULL) {
        head=node;
    }
    else {
        while(ptr->next != NULL) {
            ptr = ptr->next;
        }
        ptr->next = node;
    }
}

Node* create(int a) {
    Node *node;
    node = (Node*)malloc(sizeof(Node));
    node->data = a;
    node->next = NULL;
    return node;
}

int main() {
    Node *head;
    head = NULL;
    int i;
    for(i=0; i<10; i++) {
        Node *node;
        node = create(i);
        add(head, node);
    }
}

Problem is : head is getting redefined in the function add, everytime add is called. why ?

0

1 Answer 1

6

Because add is receiving a copy of your pointer when you call it. You set head in that function, but that changes the local copy, not other variable named head in main(). You would need to do something like this (I just put the lines to change; the rest look okay):

  void add(Node **head, Node *node) {
    *head = node;
  }



int main() {
    add(&head, node);
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Can I avoid using ** in some other way of implementing linkedlist ?
I guess I can avoid using ** but not directly assigning to head but instead use pointers relative to head.
@YugalJindle: In C, I'm not sure how to avoid passing in a pointer to your head pointer elegantly. In C++ you could use a reference. In C, the only other thing I can think of is to have your add function return the new head, then calls look like head = add(head, node);. But, that's probably worse.

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.