I try to create a little game and I have a problem I can't solve.
The objective is to hide a word by stars, one by letter, but when I try to show the hidden word, the console give me more characters than I expect.
It is perfectly fine to initialize an array that way in C, but what strlen() returns is not big enough to hold a C string. You need one more character to hold the terminating null:
char hide_answer[word_size+1];
..and you need to actually write it in there: hide_answer[word_size] = '\0';
(also, don't forget to #include <string.h> for strlen)
Your problem is likely that hide_answer[] dose not have a '\0' terminating the char array. printf() will output characters until it finds a null character to stop at, hence the junk at the end of the line. Soo make your array large enough for the string and a null character ('\0') and add the null character to the end of the array.
Edit:
tvrameshmc wrote:
Its wrong to initialize an array like this with dynamically changing variables.
The problems in the code
1. You did not include string.h for strlen()
2. You cannot declare hide_answer like that, check the way i did it
3. The last character of the string should be \0 as printf will print characters till it encounters a \0 in the memory.