Hey, I came across a weird error in a workshop for a comp sci class. C was a new code introduced to us a few weeks ago, so we are still newbies at this. The error I came across was in a basic challenge question they had, where we had to take an input string, and concatenate it multiple times based on how long it was. Basically, if your input was "hey", you would end up with "hhehey".
So, what I did was to first create two arrays. One to get the input string, and one to store the result from concatenation. Something I noticed was that I was getting unknown characters outputted in the terminal if I initialised my result array to be larger than 344.
Here is my code
Code:
#include<stdio.h>
#include<string.h>
int main(){
char input[80];
char result[370];
printf("Enter a word or small sentence: ");
fgets(input,80,stdin);
int i;
for (i=0;i<strlen(input);i++){
strncat(result,input,i);
}
printf("%s",result);
return 0;
}
In it's current state, if I compile it, and input "hello" into it, it does this.
I was able to get it to work fine by decreasing the size that I initialised the result array to. If I set it to 300, it worked without missing a beat. However, I'd really like to understand why this would cause an error.
If anyone knows why, I would be most grateful If you would be able to pass on that information.
Thank you.