Answer to Question #198587 in C for ABDULQADIR BUTT

Question #198587

Write a function called str_rev() that takes a pointer to a string as input and reverses the string in-place (this change should be reflected in the original string that was passed to the function, not to a copy of the string). No library functions for string reversal should be used. The function should also return a pointer to the reversed string.

Function prototype is given below:

char * str_rev(char * str);


1
Expert's answer
2021-05-25T13:05:26-0400
#include <stdio.h>

char* str_rev(char* str)
{
    char* begin = str;
    char* end   = str;

    while(*end != 0)
    {
        ++end;
    }   

    for(--end; begin < end; ++begin, --end)
    {
        char tmp = *begin;
        *begin = *end;
        *end = tmp;
    }
    
    return str;
}

int main()
{
    char* data = "Test string";
    printf("Source: '%s'\n", data);
    printf("Result: '%s'\n", str_rev(data));
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS