读取与scanf函数的字符串 [英] Reading a string with scanf
问题描述
我是一个有点困惑的东西。我是读一个C字符串scanf()的正确的方式沿
I'm a little bit confused about something. I was under the impression that the correct way of reading a C string with scanf() went along the lines of
(心中永远的可能缓冲区溢出,这只是一个简单的例子)
(never mind the possible buffer overflow, it's just a simple example)
char string[256];
scanf( "%s" , string );
但是,以下似乎太工作,
However, the following seems to work too,
scanf( "%s" , &string );
这只是我的编译器(GCC),纯粹是运气,还是其他什么东西?
Is this just my compiler (gcc), pure luck, or something else?
在此先感谢
推荐答案
这是阵腐朽为指针,以它的第一要素,所以 scanf函数(%S,字符串)
等同于 scanf函数(%S,&安培;串[0])
。在另一方面, scanf函数(%S,&安培;字符串)
将指针传递到 - 的char [256]
,但它指向同一个地方。
An array "decays" into a pointer to its first element, so scanf("%s", string)
is equivalent to scanf("%s", &string[0])
. On the other hand, scanf("%s", &string)
passes a pointer-to-char[256]
, but it points to the same place.
然后 scanf函数
,处理它的参数列表的尾部时,会尽量拉出一个的char *
。这就是当你在字符串已经通过正确的事
或&放大器;字符串[0]
,但是,当你字符串你根据什么说的语言标准并不能保证,即指针&放大器;字符串$ C在
&放过去了$ C>和
&放大器;字符串[0]
- 指针到开始在同一地点不同类型和大小的物体 - 重新presented以同样的方式
Then scanf
, when processing the tail of its argument list, will try to pull out a char *
. That's the Right Thing when you've passed in string
or &string[0]
, but when you've passed in &string
you're depending on something that the language standard doesn't guarantee, namely that the pointers &string
and &string[0]
-- pointers to objects of different types and sizes that start at the same place -- are represented the same way.
我不相信,我曾经遇到过哪些不工作的系统,并在实践中你可能是安全的。尽管如此,这是错误的,它可能会失败在某些平台上。 (假设的例子:。一调试实现,包括与每一个指针类型的信息我的认为的在对符号Lisp机器C实现做了这样的事情)
I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)
这篇关于读取与scanf函数的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!