I know this question has been asked many times before, but I just have a few questions about my code below.
So the code below doesn't work because in my while loop I have str != end
instead of str < end
. Why does it have to be str < end
? I'm confused because it seems like the condition str != end
should work the same way, since the pointers will eventually be pointing at the same position.
My second question is why we have to do while(*end){end++;}
instead of while(end){end++}
. Isn't the pointer invalid when we move past the length of end anyway? What is while(end){end++}
doing if it's not correct?
My last question is that in other variations of this code, I've seen a condition added to the top of this function that says if(!(*str)){return;}
. Is this necessary? My code seems to handle the empty string fine without this. Also, similar to *end
vs end
, why do we have to do !(*str)
instead of !(str)
?
void reverse(char *str){
char *end = str;
while(*end){
end++;
}
end--;
while(str != end){
char tmp = *str;
*str = *end;
*end = tmp;
str++; end--;
}
}