在C中使用“gets”表示String输入

我一直试图从用户使用fgets获取字符串输入,但fgets不等待输入,所以在投资时我了解到似乎工作正常的getsfunction。 我的问题是:1。如果我输入超过10个字符,如果我声明只有十个元素的数组,为什么gets工作。 这是我的代码

 #include int main(void){ char name[10]; printf("Please enter your name: "); gets(name); printf("\n"); printf("%s", name); return 0; } 

我在测试时的输入:morethantenletters
将输出:’morethantenletters’
当然,这应该会导致一些错误,不是吗? 由于name只有十个元素长。

2.我的下一个问题是,当我使用gets(&name)而不是gets(name)时,我的代码也可以工作 – 我不明白为什么。 &name发送&name的地址。
虽然name只是发送它的价值,不是吗?

这正是您应该始终使用fgets替换gets 。 数组name只有10个元素,但是你试图在其中存储超过它的能力。 fgets防止程序缓冲区溢出,但得不到。

当你以这种方式使用gets时,它是未定义的行为,不要使用它。

 Since name is only ten elements long. 

任何超过10接受都将是缓冲区溢出并可能导致运行时问题。 所以要确保你的尺寸合适。 提示:改为使用getlinefgets

 while name is just sending the value of it, no? 

对于char数组, name也是其起始位置的地址。