I want to inverse a string, so I wrote the following:
#include<stdio.h>
#include<conio.h>
#include<string.h>
char *inverseString(char *s);
char *inverseString(char *s)
{
char *s1;
int i = 0;
s1 = (char*)malloc (strlen(s)+1);
int j= strlen(s)-1;
for (; j>=0; j--) // dont know why for(; j> 0; j--) not work
{
s1[j] = s[i];
i++;
}
return s1;
}
void main(void)
{
char string[30];
printf("string: ");
gets(string);
printf("inverse string is : %s",inverseString(string));
getch();
}
But the result has a weird character at the end.
How can i fix it?
Thanks