I found this on the Internet today via Twitter.
It works. Well more or less. I can imagine cases where it might not but they include other problems. It’s not very efficient. A simple bit of code like this should do the trick with a lot less effort.
It also avoids the horrible memory link of a malloc without a corresponding free to give the memory back. Yes, the example is in C and not one of those cool languages with garbage collection.
These sorts of solutions appeal to some beginners. When I shared this I heard from people who have seen similar code for things like separating characters in a number. Why do they do things like this? Mostly it is because they don’t know better. That doesn’t mean they may not know other tools so much as it means they don’t know how to apply the tools they do know. So they look for solutions and grab the first one they find.
Often students will argue that “it works” means something should get full credit. The rubric I’m using this year (borrowed from Harvard’s CS50 course) includes an explicit look on how efficient the solution is. I want to encourage students to look beyond the first solution they come up with and think about efficiency.