Char arrays and scanf function in C

后端 未结 4 1883
春和景丽
春和景丽 2021-01-13 17:49

I expected to get errors in following code, but I did not. I did not use & sign. Also I am editing array of chars.

#include <         


        
4条回答
  •  佛祖请我去吃肉
    2021-01-13 18:20

    When you pass arrays to functions in C, they decay to pointers to the first item.

    Therefore for:

    char name[] ="yasser";
    

    scanf("%s", name) is the same as scanf("%s", &name[0]) and either of those invocations should send shivers down your spine, because unless you control what's on your stdin (which you usually don't), you're reading a potentially very long string into a limited buffer, which is a segmentation fault waiting to happen (or worse, undefined behavior).

提交回复
热议问题