将地址传递给数组而不是数组会引起问题吗? [英] Can it cause problems to pass the address to an array instead of the array?
问题描述
我遇到了以下代码:
char str[600];
scanf("%s", &str);
当然,这会发出以下警告:
Of course, this emits this warning:
a.c:6:17: warning: format specifies type 'char *' but the argument has type
'char (*)[600]' [-Wformat]
scanf("%s", &str);
~~ ^~~~~~~
我知道正确的方法是删除&
并键入 scanf(%s,str)
。但这确实有效,所以我的问题是这是否可能引起任何问题。它是未定义的行为吗?当我将 str
切换到指针而不是数组时,(显然)它不起作用。但这会在使用数组时引起任何问题吗?
I know that the correct way is to remove the &
and type scanf("%s", str)
instead. But it does work, so my question is if this could cause any problems. Is it undefined behavior? When I switched str
to a pointer instead of an array it (obviously) did not work. But can this cause any problem when using an array?
推荐答案
是的,代码为未定义的行为。对应于%s
的参数必须具有类型 char *
。这在C17 7.21.6.2/12中的 s
说明符下进行了描述:
Yes, the code is undefined behaviour. The argument corresponding to %s
must have the type char *
. This is described in C17 7.21.6.2/12 under the s
specifier:
[...]相应的参数应为指向字符数组的初始元素的指针,该元素的大小应足以接受该序列,并应包含一个终止的空字符,该字符将自动添加。
[...] the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically.
可以很清楚地说明指针应该具有指针到字符的类型,而不是指向整个数组。
which says fairly clearly that the pointer should have pointer-to-character type, and not point to the whole array.
未定义的行为表示可能发生任何事情。它的表现可能就像您省略了&
一样,或者它可能会格式化硬盘。
Undefined behaviour means that anything can happen. It might behave as if you omitted the &
, or it might format your hard drive.
鉴于此在这种情况下避免未定义的行为非常容易,我真的看不出有什么理由参与这种情况下是否可以依赖未定义的行为的争论。
Given that it is extremely easy to avoid undefined behaviour in this case, I don't really see any reason to engage in arguments about whether it is OK to rely on the behaviour of undefined behaviour in this situation.
这篇关于将地址传递给数组而不是数组会引起问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!