How do you reverse a string without requiring a separate buffer to hold the reversed string?


This question is really a test of pointer arithmetic.

Using 2 char pointers, one at the start and one at the end of the string move them towards each other while swapping the characters, easy!

Be sure to check that your input is not null or empty and remember that the last character will be at strlen -1.

void ReverseInPlace(char* pInput)
{
    if (NULL == pInput || !(*pInput))
        return;
    
    char* pEnd = pInput + strlen(pInput) - 1;
    
    while (pEnd > pInput)
    {
        char temp = *pInput;
        *pInput = *pEnd;
        *pEnd = temp;
        pInput++;
        pEnd--;
    }
}