将*& array分配给指针 [英] Assigning *&array to a pointer

查看:92
本文介绍了将*& array分配给指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下摘录来自 Harbinson,斯蒂尔C:A参考手册(第5版).根据这本书,p的两个分配是等效的.

The following excerpt is from Harbinson, Steele C: A Reference Manual (5th Edition). According to the book the two assignments to p are equivalent.

7.5.6地址运算符

int a[10], *p;
p = a; p = *&a;

但是,根据C常见问题解答问题6.12 a属于此类指向int的指针,而&a的类型是指向int的数组的指针.

Yet, according to the C faq Question 6.12 a is of type pointer to int whereas &a is of type pointer to array of int.

所以我们应该在第二个赋值p = *&a中遇到类型错误,因为我们试图将int的数组赋给指针.

So we should get a type error in the second assignment p = *&a because we are trying to assign an array of int to a pointer.

为什么分配p = *&a是正确的?

推荐答案

引用C11,第6.5.3.2章,地址和间接操作符

Quoting C11, chapter §6.5.3.2, Address and indirection operators,

一元*运算符表示间接. [....]如果操作数的类型为类型的指针" ,则结果的类型为类型的类型" . [....]

The unary * operator denotes indirection. [....] If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. [....]

因此,对于p = *&a;

  • &a是指向"int s数组"的指针.
  • *&a是数组类型.
  • &a is a pointer to "array of ints".
  • *&a is an array type.

现在,当在分配的RHS中使用时,数组类型会衰减为指向数组第一个元素int *的指针.

Now, when used in RHS of assignment, an array type decays to pointer to the first element of the array, an int *.

引用C11,第6.3.2.1章

Quoting C11, chapter §6.3.2.1

除了它是sizeof运算符,_Alignof运算符或 一元&运算符,或者是用于初始化数组的字符串文字,该表达式具有 类型类型数组" 转换为类型为类型指针" 的表达式 数组对象的初始元素,不是左值. [...]

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [...]

因此,没有警告/错误报告.

Hence, there's no warning/ error reported.

这篇关于将*& array分配给指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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