Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making a function that reverses the order of chars in a char array

I’ve been really struggling with understanding pointers. My function is supposed to reverse the order of chars, so if w is green it will reverse to neerg. The function I have looks right to me, but its not swapping the chars. Anyone see what’s wrong?

void mirror(char *w){
    char *p=w;
    while(*p!='\0'){
        p++;
    }
    p--;
    while(*w!='\0'){
        char temp=*p;
        *p=*w;
        *w=temp;
        w++;
        p--;
}
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

while(*w!='\0') {

You don’t want to wait to the end of the string, otherwise, you’ll wind up swapping all the characters twice.

Here’s a hint. You want to break when "w" gets ahead of "p". Let me know if that doesn’t make the fix more obvious.

Other bug. Special case the empty string by exiting immediately and before doing pointer math and deferences.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading