[Solved] Why doesn’t gets() take a char pointer argument if it can take a char array?


The gets function expects s to point to a character array that can accept a string. But in this case, s is uninitialized. So gets tries to dereference an uninitialized pointer. This invokes undefined behavior.

If you were to set s to point to a preexisting array or if you used malloc to allocate space, then you can write to it successfully.

In contrast, if s is defined as an array, it decays to a pointer to the first element of the array when passed to gets. Then gets is able to write to the array.

Note however that gets is unsafe because it makes no attempt to verify the size of the buffer you pass to it. If the user enters a string larger than the buffer, gets will write past the end of the buffer, which again invokes undefined behavior.

You should instead use fgets, which accepts the size of the buffer as a parameter.

solved Why doesn’t gets() take a char pointer argument if it can take a char array?