Using “gets” for String input in C

陌路散爱 提交于 2019-12-25 02:22:38

问题


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?


回答1:


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.

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




回答2:


Since name is only ten elements long. 

Anything accepted more than 10 will be buffer overrun and may cause run time issues. So make sure your size is right. hint: Use getline or fgets instead.

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

For char arrays, name is also address to its starting position.



来源:https://stackoverflow.com/questions/21085028/using-gets-for-string-input-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!