R G B element array swap

前端 未结 3 1501
深忆病人
深忆病人 2021-01-17 04:16

I\'m trying to create this c++ program to perform the description below. I am pretty certain the issue is in the recursive, but uncertain how to fix it. I\'m guessing it j

3条回答
  •  粉色の甜心
    2021-01-17 04:22

    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 cases 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 cases you have two situations where you'll end up in an endless loop:

    1. In the else if( *prv_ptr == *ptr_ca ) branch you simply continue; without changing the pointer.

    2. In the else branch you do ptr_ca--;, but then in default you call ptr_ca++; again.
      (Note that even with breaks 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 breaks, 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!

提交回复
热议问题