Search code examples
carraysstringgets

Why does using gets() twice in a program to take inputs for two different arrays returns only the second input even for the first array?


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);
}

Solution

    • Don't use 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.
    • Your arrays have no space. Their declarations are technically illegal in C (you can't have zero-sized arrays or empty initializers), but compilers tend to allow them as extensions. In any case, C arrays don't grow dynamically to fit your needs; C is too low-level for that.
    • As such, 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.