I have failed.

Published 2009-08-10 on Farid Zakaria's Blog

Although I love C# and how it does a good job in hiding a lot of the intricasies of pointers that C++ enjoys exposing. I prefer to have things hidden from me only when I know I understand what is going on. Today was a rude wakeup.
I hadn’t thought it had been that long in which I had written any C++; I guess I was mistaken.

Today I had the pleasure of completely implementing a simple linked list in C++ completely wrong.

In my defense, I really only faulted on aspect; however this aspect I guess now seems very silly to have gotten wrong and I am actually not even sure how I become misinformed when the right answer is so obvious.

Passing pointers by reference

For some delusional reason, I was under the impression that the only difference of passing a pointer and passing a value by reference is that the compiler would hide all the *’s and -> for code readibility.
Turns out (like always) apparently there is more at work than I understood.

Passing a pointer is pretty much passing a value and a local copy is made onto the method’s call stack. Where I err’d is in attempting to re-assign pointer values within the method.

What I should have done was clearly too either pass in a pointer to the pointer or in my case I chose to do:


Node*  Node::FindNode(Node*& head, int index)
{
	Node* tempP= head;
	for (int i = 0 ; (i <= index) && (head->nextP != NULL); i++)
	{
		if (i == index) 
		{
			return tempP;
		}
		tempP = tempP->nextP;
	}
	return 0;
}

Now to be fair. I decided to implement LinkedLists in such a way so that the head never needs to be reassigned once declared. This is obviously a stupid way of doing it; with the logical solution to always just return the pointer to the new head.

Anyways, at least I can say that I ended up learning the right semantics.