在 C 和 C++ 中通过 index[array] 访问数组 [英] Accessing arrays by index[array] in C and C++
问题描述
有些面试官不管什么原因都喜欢问这个小技巧:
There is this little trick question that some interviewers like to ask for whatever reason:
int arr[] = {1, 2, 3};
2[arr] = 5; // does this line compile?
assert(arr[2] == 5); // does this assertion fail?
据我所知,a[b]
被转换为 *(a + b)
并且由于加法是可交换的,所以它们的顺序并不重要,所以 2[a]
实际上是 *(2 + a)
并且效果很好.
From what I can understand, a[b]
gets converted to *(a + b)
and since addition is commutative, it doesn't really matter their order, so 2[a]
is really *(2 + a)
and that works fine.
C 和/或 C++ 的规范保证这可以工作吗?
Is this guaranteed to work by C and/or C++'s specs?
推荐答案
是的.6.5.2.1 第 1 段(C99 标准)描述了 []
运算符的参数:
Yes. 6.5.2.1 paragraph 1 (C99 standard) describes the arguments to the []
operator:
其中一个表达式的类型应为指向对象type
的指针",另一个表达式应为整数类型,结果的类型为type
".
One of the expressions shall have type "pointer to object
type
", the other expression shall have integer type, and the result has type "type
".
6.5.2.1 第 2 段(强调):
6.5.2.1 paragraph 2 (emphasis added):
后缀表达式后跟方括号中的表达式 []
是下标数组对象的元素的指定.下标运算符[]
的定义是 E1[E2]
与 (*((E1)+(E2)))
相同.由于转换规则适用于二进制 +
运算符,如果 E1
是一个数组对象(相当于,指向数组对象的初始元素),E2
是一个整数,E1[E2]
指定 E2
-thE1
的元素(从零开始计数).
A postfix expression followed by an expression in square brackets
[]
is a subscripted designation of an element of an array object. The definition of the subscript operator[]
is thatE1[E2]
is identical to(*((E1)+(E2)))
. Because of the conversion rules that apply to the binary+
operator, ifE1
is an array object (equivalently, a pointer to the initial element of an array object) andE2
is an integer,E1[E2]
designates theE2
-th element ofE1
(counting from zero).
它没有说要求 []
的参数顺序是合理的.
It says nothing requiring the order of the arguments to []
to be sane.
这篇关于在 C 和 C++ 中通过 index[array] 访问数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!