The function is incorrect.
Firts of all returns a 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 return line must end with zero. However, you declare an array that has no room for null termination.
Also this array is mostly misdefined
char string[6] = "kitten";
since it does not include zero completion.
And finally, this is a poor function design.
If you want to copy the source string to the destination string, then both character arrays must be declared as function parameters. In addition, the source array must be declared as a constant array.
The function might look like this
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 can define a function in such a way as to invert the original string. for instance
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; }
Note that string literals are immutable in C and cannot be changed. Any attempt to change the string literal results in undefined program behavior.
Here is a demo 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 ) ); }
Program exit
Hello gilianzz zznailig olleH Hello gilianzz