I am struggling to understand the code below which is used to reverse a null-terminated string. I have written comments explaining the lines I am struggling to understand.
void reverse(char *str)
{
char *end = str;
char tmp;
if (str) // I don't understand what is happening within this if loop and how this is carried out for `str` which is not Boolean
{
while (*end) // I dont know what this means either
{
++end;
}
--end;
while (str < end)
{
tmp = *str
*str++ = *end //I am confused as to why this is not just *str = *end
*end-- = tmp; //Similarly, why is this not *end = tmp
}
}
}
if (str) means
Check if str a pointer to char is not NULL. Same as: if (str != NULL)
while (*end) check that the char pointed to by end is not the null-terminating character. Same as: while (*end != '\0')
*str++ = *end Assign the char pointed to by end to str and then advance str pointer by 1 char. *end-- advances end backwards by 1 char.
while (str < end) Compare the addresses as numbers (and not the values the pointers point to). This only makes sense if both pointers refer to different positions in the same memory block e.g. a c string in this case or any array. If str points to the 1st element of the string and end to the 2nd, then str < end will be true. The actuals chars in the 1st and 2nd positions will are not taken into account
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With