Linked List in C: What happens when we assign the current node to a temporary node pointer? -
i have been given task write function reverse doubly-linked list. wrote function , named reverse(). function given below:
struct node* reverse(struct node** head_ref){     struct node *current=*head_ref;     struct node *tempnode=(struct node *)malloc(sizeof(struct node));     if(current->next == null){         return current;     }     while(current->next != null){         //tempnode=current;         tempnode->key=current->key;         tempnode->data=current->data;         tempnode->next=current->next;         tempnode->prev=current->prev;         current->next=current->prev;         current->prev=tempnode->next;         current=tempnode->next;     }     current->next=current->prev;     current->prev=null;     *head_ref =current;     return current; } where struct node** head_ref parameter takes reference of head node &head argument. function works fine. question here instead of doing 
tempnode->key=current->key; tempnode->data=current->data; tempnode->next=current->next; tempnode->prev=current->prev; why can't tempnode=current;? when try doing instead function doesn't produce expected result.
tempnode = current assign pointer, means both tempnode , currect pointing same address in memory.
tempnode = curr; // tempnode = 1036;    1020   1028   1036   1044 +------+------+------+------+ |      |      | curr |      | +------+------+------+------+                  ^                  | tempnode --------- you need tempnode have same values have deep copy, doing.
tempnode->key=current->key; tempnode->data=current->data; tempnode->next=current->next;         // copy content of node tempnode->prev=current->prev;         // in part of memory    120    ....   1028   1036   1044 +------+------+------+------+------+ | temp |      | curr |      |      | +------+------+------+------+------+ they have same values pointing address.
i can see overwiting pointers, shouldnt becouse loosing address of allocated memory -> cant free anymore.
store temp variable , after remove node, can free memory.
Comments
Post a Comment