What you are trying to do is not reversing a string. Neither string is reversed in your program. You are trying to copy one string in another string in the reverse order.
So the sring where you are going to copy the original string in the reverse order shall have enough space to store the copied characters.
However in your function
char* strrev(char *str)
{
char *str1
//...
pointer str1 was not initialized and does not point to an extent of memory of the appropriate size.
So your program has undefined behaviour.
Take also in account that function gets is unsafe and is not supported by the C standard any more. Use function fgets instead.
If your compiler supports Variable Length Arrays (VLA) then the program can look the following way
#include <stdio.h>
#include <string.h>
char * reverse_copy( char *s2, const char *s1 )
{
size_t n = strlen( s1 );
size_t i = 0;
for ( ; i < n; i++ ) s2[i] = s1[n-i-1];
s2[i] = '\0';
return s2;
}
int main( void )
{
char s1[1000];
printf( "Please enter a String: " );
fgets( s1, sizeof( s1 ), stdin );
size_t n = strlen( s1 );
if ( n != 0 && s1[n-1] == '\n' ) s1[n-1] = '\0';
char s2[n + 1];
puts( s1 );
puts( reverse_copy( s2, s1 ) );
return 0;
}
If to enter for example
Hello Asfakul Islam
then the output will look like
Please enter a String: Hello Asfakul Islam
Hello Asfakul Islam
malsI lukafsA olleH
Otherwise if your compiler does not support VLA(s) you need to dynamically allocate an array of the appropriate size. In this case the program can look for example the following way
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char * reverse_copy( char *s2, const char *s1 )
{
size_t n = strlen( s1 );
size_t i = 0;
for ( ; i < n; i++ ) s2[i] = s1[n-i-1];
s2[i] = '\0';
return s2;
}
int main( void )
{
char s1[1000];
printf( "Please enter a String: " );
fgets( s1, sizeof( s1 ), stdin );
size_t n = strlen( s1 );
if ( n != 0 && s1[n-1] == '\n' ) s1[n-1] = '\0';
char *s2 = malloc( ( n + 1 ) * sizeof( char ) );
puts( s1 );
puts( reverse_copy( s2, s1 ) );
free( s2 );
return 0;
}
getsis discouraged because this function cannot prevent buffer overrun.strrevwill never run for strings with a length of more than one characters. For zero-length string you will have undefined behavior.