Sorry to put it blunt, but that code is a mess. And I don't mean the mistakes, those are forgivable for beginners. I mean the formatting. Multiple statements in one line make it super hard to read and debug the code. Short variable names that carry no immediate intrinsic meaning make it hard to understand what the code is supposed to do. using namespace std;
is very bad practise as well, but I can imagine you were taught to do this by whoever gives that course.
1st problem
Your case
s don't break
, thus you execute all cases for R
, and both G
and default
for G
. Also your code will never reach the last 2 lines of your loop, as you continue
out before in every case.
2nd problem
You have an endless loop. In both case
s you have two situations where you'll end up in an endless loop:
In the else if( *prv_ptr == *ptr_ca )
branch you simply continue;
without changing the pointer.
In the else
branch you do ptr_ca--;
, but then in default
you call ptr_ca++;
again.
(Note that even with break
s you would still call ptr_ca++;
at the end of the loop.)
In both cases the pointer doesn't change, so once you end up in any of those conditions your loop will never exit.
Possible 3rd problem
I can only guess, because it is not apparent from the name, but it seems that prv_ptr
is supposed to hold whatever was the last pointer in the loop? If so, it seems wrong that you don't update that pointer, ever. Either way, proper variable names would've made it more clear what the purpose of this pointer is exactly. (On a side note, consistent usage of const
can help identify such issues. If you have a variable that is not const
, but never gets updated, you either forgot to add const
or forgot to update it.)
How to fix
Format your code:
- Don't use
using namespace std;
.
- One statement per line.
- Give your variables proper names, so it's easy to identify what is what. (This is not 1993, really, I'd rather have a
thisIsThePointerHoldingTheCharacterThatDoesTheThing
than ptr_xy
.)
Fix the aforementioned issues (add break
s, make sure your loop actually exits).
Then debug your code. With a debugger. While it runs. With breakpoints and stepping through line by line, inspecting the values of your pointers as the code executes. Fancy stuff.
Good luck!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…