0

Plz anyone tell me what is the problem with this code coach problem code?

#include <stdio.h> #include <string.h> int main() { char str[100]; gets(str); char ans[100]; int len = strlen(str); int i,j,k,temp; j=0; for(k=0;k<len/2;k++) { temp = str[k]; str[k] = str[len-k-1]; str[len-k-1] = temp; } for(i=0;i<len;i++) { if((str[i]>=65 && str[i]<=90) || (str[i]>=97 && str[i]<=122) || str[i]==32) { ans[j]=str[i]; j++; } } puts(ans); return 0; }

25th Apr 2022, 3:33 AM
NERD 2 NERD
5 Answers
+ 2
The problem is that the string in `ans` is not null-terminated, so depending on what values where in that memory beforehand, you write more characters than you actually want. Either zero-initialize the array at the start or explicitly store a null character at the end of the string to make it work, i.e char ans[100] = {0}; or ans[j] = '\0'; puts(ans);
25th Apr 2022, 6:02 AM
Shadow
Shadow - avatar
0
I tested your snippet with default
25th Apr 2022, 3:48 AM
Ipang
0
Did it run?
25th Apr 2022, 3:51 AM
NERD 2 NERD
0
I mean did it give the required output?
25th Apr 2022, 3:51 AM
NERD 2 NERD
0
I tested your snippet with default sample "d89%l++5r19o7W *o=l645le9H" It did run, and it did output "Hello World" I don't know why you get a problem, the only possible issue I see here is the use of gets() function which is deprecated. People avoid using gets() and use fgets() instead for now. http://www.cplusplus.com/reference/cstdio/fgets/ (Edited)
25th Apr 2022, 3:54 AM
Ipang