问题描述
我对某事有点困惑.我的印象是,使用 scanf()
读取 C 字符串的正确方法遵循
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", string)
等价于scanf("%s", &string[0])
.另一方面,scanf("%s", &string)
传递了一个指向 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 *
.当您传入 string
或 &string[0]
时,这是正确的事情,但是当您传入 &string
时你依赖于语言标准不能保证的东西,即指针 &string
和 &string[0]
-- 指向不同对象的指针从相同位置开始的类型和大小 - 以相同的方式表示.
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.
我相信我从未遇到过无法运行的系统,实际上您可能是安全的.尽管如此,这是错误的,并且在某些平台上可能会失败.(假设示例:一个调试"实现,其中包含每个指针的类型信息.我认为 SymbolicsLisp Machines"上的 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 读取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!