The function is wrong.
Firts of all it returns pointer to a local array that will be destroyed after exiting the function
//,,,
char reversedString[len];
//...
return reversedString; //return pointer to first element of reversed string
Secondly the reversed string shall have terminating zero. However you declare an array that has no space for the terminating zero.
Also this array in main defined incorrectly
char string[6] = "kitten";
because it does not include terminating zero.
And at last it is a bad design of the function.
If you want to copy the source string in the destination string then the both character arrays should be declared as function parameters. Moreover the source array should be declared as a constant array.
The function can look the following way
char *reverseCopyString( char s1[], const char s2[] )
{
size_t n = strlen( s2 );
for ( size_t i = 0; i < n; i++ ) s1[i] = s2[n - i - 1];
s1[n] = '\0';
return s1;
}
Or you could define the function such a way that ir reverse the source string. For example
char *reverseString( char s[] )
{
size_t n = strlen( s );
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = c;
}
return s;
}
Take into account that string literals are immutable in C and may not be changed. Any attempt to change a string literal results in undefined behaviour of the program.
Here is a demonstrative program
#include <stdio.h>
#include <string.h>
char *reverseCopyString( char s1[], const char s2[] )
{
size_t n = strlen( s2 );
for ( size_t i = 0; i < n; i++ ) s1[i] = s2[n - i - 1];
s1[n] = '\0';
return s1;
}
char *reverseString( char s[] )
{
size_t n = strlen( s );
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = c;
}
return s;
}
int main( void )
{
char *s1 = "Hello gilianzz";
char s2[16];
puts( s1 );
puts( reverseCopyString( s2, s1 ) );
puts( reverseString( s2 ) );
}
The program output is
Hello gilianzz
zznailig olleH
Hello gilianzz
strlen()problem is fixed, stackoverflow.com/questions/25603908/… is another reverse-string question with your other bug (returning a local array).reversedStringvariable is good, safe, well-defined behavior?