I’m having some trouble copying pointers’ contents. I’m simply trying this:
char* vigia1;
char* vigia2;
And..
char* aux = (char*) malloc (strlen (vigia1)+1);
aux=vigia1;
vigia1=vigia2;
vigia2=aux;
free (aux);
vigia1, vigia2 are pointers to a char pointer. They both have a malloc greater than their maximum possible size, that’s OK.
Since I’m trying to make an order for a list, I need to make this change to order the nodes’ content. But I’m getting confused: after the free(aux) , vigia2 doesn’t have any value. I think I must be pointing vigia2 to the memory region where aux is, region that ‘disappear’ after the free. So what should I do?
Thanks!
Pointers, pointers, bad with them, worse without them
A pointer is a number that stores where in memory sth is stored, with that in mind, let’s delve into what you’ve done there:
Good, you’ve created space somewhere in a part of the memory called heap, and stored the address of the newly created memory space at aux.
Ops, now you’ve overwritten the address of the memory space you’ve “created” with the number stored at vigia1, that happens to be an address to another memory space.
Now you’re assinging to vigia1 the value of vigia2, another address of some memory space out there.
And, by the end of it, you make vigia2 point to the memory region previously pointed by vigia1.
Now, you’re freeing the memory pointed by aux. Wait a second, on the line above this one you’ve just made vigia2 point to this same address. No wonder it holds nothing useful 🙂
Trying to help you with what you want to do:
So long you don’t have any constraint that obliges you to mantain your list nodes ordered in memory, you don’t need to copy the content of the node, just make the pointer of the first node point to the memory region of the second node.
A perfect swap would be: