Home > Blockchain >  Don't understand why changing pointer of one variable affects the variable it's copied fro
Don't understand why changing pointer of one variable affects the variable it's copied fro

Time:11-10

I have this piece of code that helps me to sort a linked list whose nodes contain a singular word. From my understanding of insertion sort, I've managed to come up with this which works fine, but there is a part where I've copied from online and need help in understanding it.

Node* insertion_sort(Node* head) {
    Node* dummy;
    dummy= malloc(sizeof(Node));
    if (dummy == NULL) {
        printf("Memory allocation error");
    }
    dummy->next = head;
    Node* last_sorted = head;
    Node* current = head->next;
    while (current != NULL) {
        if(strcmp(last_sorted, current) <= 0) {
        last_sorted = current;
        }
        else {
            Node* prev = dummy;
            while (strcmp(prev->next->word, current) < 0) {
                prev = prev->next;
            }
            last_sorted->next = current->next;
            current->next = prev->next;
            prev->next = current;
        }
        current = last_sorted->next;
    }
    return dummy->next;
}

In the line

prev->next = current;

Why would it also change the value of where my dummy node points to? Wouldn't the 2 nodes be independent of one another? I suspect this is due to how pointers work as this is very new territory for me.

I have tried running through the debugger and saw the changes but I do not understand why/how does this occur.

CodePudding user response:

The pointers are pointing to the exact same object, not copies of the object. You can confirm this by looking at the contents of the prev and dummy variables - they will have the same value. When performing the assignment, it's changing the single object that both of the variables are pointing to.

CodePudding user response:

dummy is a pointer to a node - it's not a node. prev is a pointer to a node - it's not a node.

The nodes are created by malloc and they don't have names. That's why it's important to keep track of which pointers are pointing to what.

If you do:

Node* dummy = malloc(sizeof(Node));
Node* prev = dummy;
prev->word = "hello";

then the node's word is "hello", and both prev and dummy point to the node, so dummy->word is also "hello". prev->word and dummy->word are the exact same variable.

If this is still too confusing because the node doesn't have a name, you may think about pointers to variables which have names:

int i;
int* p = &i;
int* q = &i;

both *p and *q and i are the same variable. p isn't q, but *p is i and *p is also i, so *p is *q.

If you do *p = 42; then *q is also 42 because both of them are i.

  • Related