在 scanf() 中使用与号 [英] Using an ampersand in scanf()
问题描述
当我编译 scanf("%s", &var);
时,gcc 发回警告:
When I compile scanf("%s", &var);
, gcc sends back a warning:
warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’
然而,当我编译 scanf("%s", var);
时,没有应用警告.两段代码工作和我正在阅读的书都特别提到要使用和号,但即使在某些示例中也没有.
however when I compile scanf("%s", var);
, no warning is applied. Both pieces of code work and the book I am reading specifically says to use the ampersand, but even it doesn't in some of the examples.
我的问题是,即使书中没有指定,我是否应该继续使用&符号?
My question is, should I continue to use the ampersand, even when the book doesn't specify?
推荐答案
根据您发布的内容 var
是一个字符数组.在这种情况下,您不需要&符号,只是名称 var
将根据需要计算为 (char *).
From what you've posted var
is a char array. In that case, you don't need the ampersand, just the name var
will evaluate to a (char *) as needed.
详情:
scanf 需要一个指向将存储输入的变量的指针.在字符串的情况下,您需要一个指向内存中字符数组的指针,该数组足够大以存储读入的任何字符串.当您声明诸如 char var[100]
之类的内容时,您为100 个 char
s,其中 var[0] 指的是第一个字符,var[99] 指的是第 100 个字符.数组名称本身的计算结果与 &var[0]
完全相同,它是指向序列第一个字符的指针,正是 scanf 所需要的.所以你需要做的就是 scanf("%s", var);
,但要注意 scanf
不对输入字符串施加大小限制,所以如果用户输入一个 101 长度的字符串,你将有一个缓冲区溢出,这将导致错误,甚至更糟的是,安全问题.更好的选择通常是 fgets
允许输入字符串的大小限制.
scanf needs a pointer to the variable that will store input. In the case of a string, you need a pointer to an array of characters in memory big enough to store whatever string is read in. When you declare something like char var[100]
, you make space for 100 char
s with var[0] referring to the first char and var[99] referring to the 100th char. The array name by itself evaluates to exactly the same thing as &var[0]
, which is a pointer to the first character of the sequence, exactly what is needed by scanf. So all you need to do is scanf("%s", var);
, but be aware that scanf
does not enforce size constraints on input strings, so if the user inputs a 101 length string your will have a buffer overrun, which will result in bugs or, even worse, security problems. The better choice is generally fgets
which does allow size constraints for input strings.
这篇关于在 scanf() 中使用与号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!