Answer to Question #197789 in C for Hassam

Question #197789

Task 1: Reverse a character string.

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-24T12:47:46-0400
#include <stdio.h>

char* str_rev(char* str)
{
    char *first, *last;
    first = last = str;

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

    while(str < --last)
    {
        char tmp;
        tmp = *str;
        *str = *last;
        *last = tmp;

        ++str;
        --last;
    }
    
    return first;
}

int main()
{
    char* test_string = "12345";

    printf("Reversed string is '%s'\n", str_rev(test_string));

    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