gpt4 book ai didi

c - char数组前面的&符号会影响scanf吗?合法吗?

转载 作者:太空狗 更新时间:2023-10-29 17:02:32 25 4
gpt4 key购买 nike

我们平时输入字符串的时候,是这样操作的:

#include <stdio.h>
int main()
{
char str[256];
scanf("%s",str);
//Other Operation
}

但是,今天,在编程课上,我的一个 friend 这样写 scanf 行:

scanf("%s",&str);

它通过了编译,并且可以工作。

问题是,我想知道这在 C 中是否“合法”,或者只是未定义的行为?

最佳答案

这是未定义的行为(因为scanf()期望的类型是char *,但是你传入了一个char (*)[256]),但它通常“有效”(看起来有效),因为数组的地址通常与其第一个元素的地址相同(关于指针的数值)。

来自official documentation :

If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the space provided, the behavior is undefined.

(强调我的)

关于c - char数组前面的&符号会影响scanf吗?合法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18214684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com