The code below takes input twice and saves it in two separate arrays. When using puts() to print these arrays, puts(array1);
is returning the same vale as puts(array1);
. Why is this happening?
int main()
{
char array1[]={};
char array2[]={};
printf("Enter String 1: ");
gets(array1);
printf("Enter String 2: ");
gets(array2);
puts(array1);
puts(array2);
}
gets()
. It's impossible to use safely and will happily overflow any and all arrays you give it. Also, newer versions of C removed it completely. On GCC and Clang, try compiling with -std=c11
.gets
simply overwrites your stack with whatever is read in. And since those arrays are size 0, they are in the same location, so the second read overwrites the first.To sum up, your program exhibits lots of undefined behavior, and as such you cannot rely on it doing anything in particular.
You need to give your arrays enough space to contain the read string. You need to tell the read function not to read more than you have space for. Since that is not possible with gets
, you need to use fgets
or another function where it is possible.