一个字符语义[] [英] Semantics of char a[]

查看:147
本文介绍了一个字符语义[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我不好意思自己当解释给同事为什么

I recently embarrassed myself while explaining to a colleague why

char a[100];
scanf("%s", &a); // notice a & in front of 'a'

是非常糟糕的,而且稍微更好的方式来做到这一点是:

is very bad and that the slightly better way to do it is:

char a[100];
scanf("%s", a); // notice no & in front of 'a'

确定。为大家准备告诉我为什么scanf函数不应该反正用于安全方面的原因:缓和。这个问题其实是关于含义与& A和A

Ok. For everybody getting ready to tell me why scanf should not be used anyway for security reasons: ease up. This question is actually about the meaning of "&a" vs "a".

问题是,在我解释了为什么它不应该工作,我们试了一下(用gcc)和它的作品=))。我跑了快

The thing is, after I explained why it shouldn't work, we tried it (with gcc) and it works =)). I ran a quick

printf("%p %p", a, &a);

和它打印相同的地址两次。

and it prints the same address twice.

谁能给我解释一下这是怎么回事?

Can anybody explain to me what's going on?

推荐答案

那么,&放大器;一个情况下应该是显而易见的。你把数组的地址,正如预期。
A 是有点微妙,但得到的答复是, A 的数组。而作为任何C程序员都知道,阵列具有蜕变为指针,稍有挑衅的倾向,的例如的传递给它当作为函数参数。

Well, the &a case should be obvious. You take the address of the array, exactly as expected. a is a bit more subtle, but the answer is that a is the array. And as any C programmer knows, arrays have a tendency to degenerate into a pointer at the slightest provocation, for example when passing it as a function parameter.

所以 scanf函数(%S,A)期望一个指针,而不是一个数组,所以数组退化成一个指向数组的第一个元素。

So scanf("%s", a) expects a pointer, not an array, so the array degenerates into a pointer to the first element of the array.

当然, scanf函数(%S,&安培; A)。工作过,因为这是明确的数组的地址

Of course scanf("%s", &a) works too, because that's explicitly the address of the array.

编辑:的优越位置,是我完全没有考虑到什么样的参数类型实际上scanf函数预期。这两种情况下,得到一个指向同一个地址,但不同的类型。 (字符指针,与指针字符数组)。

Oops, looks like I totally failed to consider what argument types scanf actually expects. Both cases yield a pointer to the same address, but of different types. (pointer to char, versus pointer to array of chars).

和我会很乐意承认,我不知道有足够的了解了省略号语义(...),我一直避免瘟疫一样,所以看起来像任何类型scanf函数最终使用可转换未定义的行为。阅读的意见,并litb的回答。通常你可以信任他得到这个东东吧。 ;)

And I'll gladly admit I don't know enough about the semantics for ellipsis (...), which I've always avoided like the plague, so looks like the conversion to whichever type scanf ends up using may be undefined behavior. Read the comments, and litb's answer. You can usually trust him to get this stuff right. ;)

这篇关于一个字符语义[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆