使用“获取"用于C中的字符串输入 [英] Using "gets" for String input in C

查看:47
本文介绍了使用“获取"用于C中的字符串输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 fgets 从用户那里获取字符串输入但是fgets并不等待输入,因此在进行调查后,我了解到 gets 函数似乎运行良好.我的问题是:1.如果我声明仅包含10个元素的数组,那么当我输入10个以上的字符时 gets 为什么起作用.这是我的代码

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;

}

我在测试时输入的内容:更多字母
将输出:"morethantenletters"
当然,这应该引起一些错误,不是吗?由于 name 仅十个元素.

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

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?

推荐答案

这就是为什么您应该始终使用 fgets 替换 gets 的原因.数组 name 仅包含10个元素,但是您试图在其中存储的存储量超出了它的能力. fgets 防止程序缓冲区溢出,但 gets 不会.

That is exactly why you should always use fgets to replace gets. The array name 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, but gets doesn't.

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

It's undefined behavior when you are using gets in this way, don't use it.

这篇关于使用“获取"用于C中的字符串输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆