Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding code to reverse string

Tags:

c++

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
        }
    }
}
like image 531
Jojo Avatar asked Feb 18 '26 19:02

Jojo


1 Answers

  1. if (str) means Check if str a pointer to char is not NULL. Same as: if (str != NULL)

  2. while (*end) check that the char pointed to by end is not the null-terminating character. Same as: while (*end != '\0')

  3. *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.

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

like image 105
Manos Nikolaidis Avatar answered Feb 21 '26 07:02

Manos Nikolaidis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!