I have failed.

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:

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.

2 Replies to “I have failed.”

  1. The VERY COMMON mistake of not passing pointers to pointers when writing linked lists functions in C++ is discussed in the book Programmer Interviews Exposed. I wouldn’t feel too bad that you made that mistake, you’re not the first nor the last to do it! I just wish you didn’t make that mistake in an interview 🙁

  2. What a coincidence. I had just finished going through Programming Interviews Exposed Second Edition; which was recommended to me by the google recruiter prior to my interviews.

    Luckily I had not made the mistake in the interviews although the interviews didn’t focus at all on pointers etc… and were purely on run time analysis and general algorithms.

    That book is a very good book.

    Anyways I guess it’s something I hadn’t encountered for a while because rarely did I even reassign pointers in a method, usually just return a pointer and then reassign.

Leave a Reply

Your email address will not be published. Required fields are marked *