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);
#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;
}
Comments
Leave a comment