[英]fixed length array in scanf.Warning with format
So I have typedefed the following : 所以我定义了以下内容:
typedef char array[25];
In my code somewhere I call scanf like this : 在我的代码中,我这样称呼scanf:
scanf("%s",array);
But I get the warning that %s was expecting a char* while I pass a char*[25].Is there any way to get rid off this warning ? 但是当我通过char * [25]时,我得到%s期望有char *的警告。是否有任何方法可以摆脱此警告?
array
is type and is not a object. array
是类型,不是对象。 you can not pass it as argument in the scanf
您不能将其作为参数传递给
scanf
array a;
scanf("%s", a);
typedef defines a data type so that you can use it to define different variables with same data types. typedef定义数据类型,以便您可以使用它来定义具有相同数据类型的不同变量。 like:
喜欢:
typedef char employee[25];
typedef char customer[25];
employee a, b;
customer y, z;
printf("Enter first employee's name: ");
scanf("%s",a);
printf("Enter customer's name: ");
scanf("%s",y);
though the datatypes are same, but defining them is elaborating things. 尽管数据类型相同,但是定义它们很麻烦。 all you need to do here is: take
array a;
您需要做的就是:取
array a;
and then scanf("%s",a);
然后
scanf("%s",a);
Hope you are clear to the core! 希望您清楚核心! :)
:)
I am assuming your code is abbreviated... 我假设您的代码是缩写...
The actual reason for the warning is that the compiler knows two things: you have a char array that is limited length, and that scanf will scan as many characters as are given in the original string; 发出警告的实际原因是编译器知道两件事:您有一个有限长度的char数组,而scanf将扫描与原始字符串中给定的字符一样多的字符; potentially overflowing the array provided for them.
可能会溢出为他们提供的数组。
This is a real issue: the compiler is quite correct. 这是一个真实的问题:编译器是正确的。
The solution is to specify the scanf format better. 解决方案是更好地指定scanf格式。 In this case I would suggest using "%24s" to tell scanf the max number of characters to read for that format element.
在这种情况下,我建议使用“%24s”来告诉scanf该格式元素读取的最大字符数。
Remember to allow for the null terminator - better, explicitly zap array[len-1] with 0. 请记住要留空终止符-更好的是,显式地将array [len-1]换为0。
There are possibly better ways to read the string than scanf. 读取字符串的方法可能比scanf更好。 Look into some of the token based methods, for example.
例如,研究一些基于令牌的方法。
HTH, Ruth 露丝·HTH
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.