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 :
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.