I have been trying to get a string input from a user using fgets
but fgets does not wait for input so upon investagation I learned of the gets
function which seems to be working fine. My questions are: 1. Why does gets
work when I input more than 10 characters if I declared an array of only ten elements. Here is my code
#include<stdio.h>
int main(void){
char name[10];
printf("Please enter your name: ");
gets(name);
printf("\n");
printf("%s", name);
return 0;
}
my input when testing: morethantenletters
will output: 'morethantenletters'
Surely, this should have caused some errors, no? Since name
is only ten elements long.
2. My next question is that my code also works when I use gets(&name)
instead of gets(name)
-- I do not understand why. The &name
is sending the address of name
.
while name
is just sending the value of it, no?
That is exactly why you should always use
fgets
to replacegets
. The arrayname
has only 10 elements, but you are trying to store in it more than it's capable of.fgets
prevents the program from buffer overflow, butgets
doesn't.It's undefined behavior when you are using
gets
in this way, don't use it.Anything accepted more than
10
will be buffer overrun and may cause run time issues. So make sure your size is right. hint: Usegetline
orfgets
instead.For char arrays,
name
is also address to its starting position.