gpt4 book ai didi

c - 为什么寄存器数组名称可以分配给指针变量而不会出现编译器错误?

转载 作者:行者123 更新时间:2023-12-01 20:07:39 25 4
gpt4 key购买 nike

我有一个关于 C 语言中 register 关键字的问题。

我发现register数组名称(例如array)可以分配给指针变量,而&array[0]则不能。

你能解释一下为什么数组名可以赋给指针吗?或者,如果有人已经解释过,请让我知道链接,以便我可以查看以获得答案。谢谢。

这是我尝试过的:

我读到cppreference其中解释了 register 关键字,它说:

register arrays are not convertible to pointers.

此外,我阅读了 C89 草案,其中写道:

The implementation may treat any register declaration simply as an auto declaration. However, whether or not addressable storage is actually used, the address of any part of an object declared with storage-class specifier register may not be computed, either explicitly (by use of the unary & operator as discussed in 3.3.3.2) or implicitly (by converting an array name to a pointer as discussed in 3.2.2.1). Thus the only operator that can be applied to an array declared with storage-class specifier register is sizeof.

这看起来我无法将寄存器数组名称分配给指针来获取其地址。

此外,为了找到答案,我在这里搜索并发现了这个问题: Address of register variable 。有很好的答案,但是我仍然找不到我想要的答案。

这是我测试过的代码。我通过 Clang 使用标志 -std=c89 编译了此代码:

register int array[10];
int* p;

p = array; // Compiled without warning or error
p = &array[0]; // Compiled with error which I expected

我预计 p = array;p = &array[0]; 都会导致编译错误,但只有 p = &array[0]; code> 发生编译错误。

最佳答案

这是 Clang 编译器中的一个错误。 GCC shows an error on both lines.

在讨论“类型的数组”到“类型的指针”的自动转换时,C 2018 6.3.2.1 说:

… If the array object has register storage class, the behavior is undefined.

此外,C 2018 脚注 124 说:

… the address of any part of an object declared with storage-class specifier register cannot be computed, either explicitly (by use of the unary & operator as discussed in 6.5.3.2) or implicitly (by converting an array name to a pointer as discussed in 6.3.2.1)…

显然,p = array;array 转换为指针,如 6.3.2.1 中所述,但是这个脚注(这是非规范的,但告诉我们意图在这种情况下非常明确)表示无法计算该指针的值。

由于 C 标准未定义该行为,因此 C 实现可以将其定义为扩展。但是,array&array[0] 之间的不一致行为表明这不是 Clang 故意的扩展,而是一个错误。

关于c - 为什么寄存器数组名称可以分配给指针变量而不会出现编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58089849/

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