C 定义中的运算符优先级
Wikipedia 声称 []
运算符优先于求值中的 *
运算符。
那么,为什么下面的语句:
char *a[3];
声明一个 3 个字符指针的数组,而不是根据运算符优先级声明一个指向 3 个字符数组的指针?
Wikipedia claims that the []
operator precedes the *
operator in evaluation.
Then, why does the following statement:
char *a[3];
declare an array of 3 character pointers, rather than a pointer to an array of 3 characters as per the operator precedence?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为,正如维基百科所说,
[]
的优先级高于*
?处理声明时,
a[3]
将在处理*
之前作为“3 的数组”进行处理。要声明指向三个字符数组的指针,必须使用括号来覆盖默认优先级:
现在括号优先于数组。
Because, as Wikipedia says,
[]
has higher precedence than*
?Processing the declaration, the
a[3]
is processed as 'array of 3' before you process the*
.To declare a pointer to an array of three characters, you have to use parentheses to override the default precedence:
Now the parentheses take precedence over the array.
以下是声明符的语法,取自标准 (§ 6.7.5):
如您所见,
[]
和()
都绑定到*
之前的声明符。取声明声明符为
*a[N]
,它符合上面的pointeropt直接声明符模式,因此被解析为< code>*(a[N]),所以a
是一个N元素的指针数组。总结:
Here's the grammar for a declarator as taken from the standard (§ 6.7.5):
As you can see, both
[]
and()
bind to the declarator before*
. Take the declarationThe declarator is
*a[N]
, which fits the pointeropt direct-declarator pattern above, and is thus parsed as*(a[N])
, soa
is an N-element array of pointer.To sum up:
我对这个问题感到困惑 - 声明的解释与运算符优先级相匹配。如果您想要一个指向数组的指针,则必须在
[]
绑定之前使用括号“将*
绑定到标识符”。I'm confused about the question - the interpretation of the declaration matches the operator precedence. If you want a pointer to an an array you have to use parens to 'bind the
*
to the indentifier' before the[]
binding.