Reverse strings in C
c, string
Solution
You need to add the null terminator:
new_str[len] = '\0';
otherwise, there is garbage after the last character, so the string is not ending
Problem
What's the problem with the following code? ``` #define N 30 int main() { char str[N], new_str[N]; int i,len; printf("Please enter 20 letters. \n"); scanf("%s", str); len = strlen(str); printf("The length of str is %d ", len); for (i=0; i< len; i++) new_str[i]=str[len-1-i]; printf("The result is: %s\n", new_str); return 1; } ``` I checked that for every string under 16 characters the program is OK, and above it returns undefined characters at the end: ``` Please enter 20 letters. 1234567891111111 The result is: 1111111987654321q=V?. ``` However, if I initialize `str, new_str` with "" the problem is solved. I still I wonder what causes the problem.