For starters the call of the function
char word[LEN];
reverse(word);
does not make a sense because neither string is passed to the function. You passed an uninitialized character array.
The function should do only one thing: reverse the passed string.
So the call of fgets
should be removed from the function and placed in main.
The function fgets
can append the new line character '\n'
to the entered string. You need to remove it.
Within the function reverse
you forgot to append the terminating zero character '\0'
to the reversed string. So this call
printf("%s\n", rev);
invokes undefined behavior.
Also the type of the returned value of the standard C function strlen
is the unsigned integer type size_t
. You should use this type instaed of the signed integer type int
.
And this declaration of the function
void reverse( char w[LEN])
also does not make a great sense because the compiler will adjust it to the following declaration
void reverse( char *w)
and in general the user can pass to the function a string of any length that can be greater than the value LEN
.
Below there is a demonstrative program that shows how the function can be written.
#include <stdio.h>
#include <string.h>
char * reverse( char *s )
{
for ( size_t i = 0, n = strlen( s ); i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = c;
}
return s;
}
int main(void)
{
enum { N = 20 };
char s[N];
fgets( s, N, stdin );
s[ strcspn( s, "\n" ) ] = '\0';
puts( s );
puts( reverse( s ) );
return 0;
}
If to enter string "Hello World!"
then the program output will be
Hello World!
!dlroW olleH